使用单个函数合并两个排序过的链表



在使用一个函数实现两个不同的链表时遇到麻烦。下列代码:

#include <bits/stdc++.h>
using namespace std;
#define node struct Node
struct Node
{
int data;
struct Node *next;
} *first = NULL, *second = NULL;

👇👇此函数用于创建链表


void create(int A[], int n, node *ptr)
{
struct Node *temp, *last;
ptr = (struct Node *)malloc(sizeof(struct Node));
ptr->data = A[0];
ptr->next = NULL;
last = ptr;
for (int i = 1; i < n; i++)
{
temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = A[i];
temp->next = NULL;
last->next = temp;
last = temp;
}
}
void display(node *ptr)
{
cout << "Your linked list: ";
while (ptr != NULL)
{
cout << ptr->data << " ";
ptr = ptr->next;
}
cout << endl;
}

我使用数组来获取元素函数,即"userInput",其中数组大小和指针将作为参数

// taking elements for the linked list👇👇👇
void userInput(int size, node *ptr)
{
int arr[size];
cout << "Input linked list element values: ";
for (int i = 0; i < size; i++)
{
cin >> arr[i];
}
//! Create the linked list
create(arr, size, ptr);
//* Display the linked list
display(ptr);
}
int main()
{
cout << "tt-----------------------n";
cout << "ttCreating the first LLn";
cout << "tt-----------------------nn";
int s;
cout << "Enter size: ";
cin >> s;
userInput(s, first);
cout << "nntt-----------------------n";
cout << "ttCreating the second LLn";
cout << "tt-----------------------nn";
cout << "Enter size: ";
cin >> s;
userInput(s, second);
return 0;
}

运行代码后,程序无法显示链表。我怎么能实现两个链表只有这个代码库?

您将列表指针作为值传递给create函数,该值是空指针。该函数不更新全局变量。您应该更改create函数以返回列表指针:

struct Node *create(int A[], int n) {
struct Node *ptr = (struct Node *)malloc(sizeof(*ptr));
ptr->data = A[0];
ptr->next = NULL;
struct Node *last = ptr;
for (int i = 1; i < n; i++) {
struct Node *temp = (struct Node *)malloc(sizeof(*temp));
temp->data = A[i];
temp->next = NULL;
last->next = temp;
last = temp;
}
return ptr;
}
// taking elements for the linked list
struct Node *userInput(int size) {
int arr[size];
cout << "Input linked list element values: ";
for (int i = 0; i < size; i++) {
cin >> arr[i];
}
//! Create the linked list
struct Node *ptr = create(arr, size);
//* Display the linked list
display(ptr);
return ptr;
}
int main() {
cout << "tt-----------------------n";
cout << "ttCreating the first LLn";
cout << "tt-----------------------nn";
int s;
cout << "Enter size: ";
cin >> s;
first = userInput(s);
cout << "nntt-----------------------n";
cout << "ttCreating the second LLn";
cout << "tt-----------------------nn";
cout << "Enter size: ";
cin >> s;
second = userInput(s);
return 0;
}

最新更新