create()函数第二次调用时,返回的链表的头节点地址为空,不知道为什么。
#include<stdio.h>
#include<stdlib.h>
#define LEN sizeof(struct ListNode)
struct ListNode
{
int value;
struct ListNode* next;
};
int n; //节点数
struct ListNode* creat(void) //建立链表(输入链表)的函数
{
struct ListNode* head, * p1, * p2;
p1 = p2 = (struct ListNode*)malloc(LEN); //第一个节点
scanf_s("%d", &p1->value);
head = NULL;
while (p1->value != 0) { //输入0时候停止建立链表
n++; //节点数
if (n == 1) {
head = p1;
}
else {
p2->next = p1;
}
p2 = p1;
p1 = (struct ListNode*)malloc(LEN);
scanf_s("%d", &p1->value);
}
p2->next = NULL; //p1=p1,结尾
return head;
}
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2)
{
if (l1 == NULL) {
// l1 为空, 最终结果就是 l2
return l2;
}
if (l2 == NULL) { //l2为空,最终结果就是l1
return l1;
}
ListNode* newHead, * newTail, * cur1, * cur2;
newHead = newTail = (struct ListNode*)malloc(LEN); //傀儡节点
cur1 = l1;
cur2 = l2;
//两链表不为空时进入循环
while (cur1 != NULL && cur2 != NULL) {
if (cur1->value < cur2->value) {
newTail->next = cur1;
newTail = newTail->next;
cur1 = cur1->next;
}
else {
newTail->next = cur2;
newTail = newTail->next;
cur2 = cur2->next;
}
}
//多出的节点直接接到新链表后面
if (cur1 == NULL) {
newTail->next = cur2;
}
if (cur2 == NULL) {
newTail->next = cur1;
}
return newHead->next;
}
int main()
{
ListNode* ptr1, * ptr2, * head1, * head2;
printf("请输入链表:\n");
head1 = ptr1 = creat();
printf("请再输入链表:\n");
head2 = ptr2 = creat();
printf("输入:");
while (ptr1 != NULL) {
printf("%d->", ptr1->value);
ptr1 = ptr1->next;
}
printf("\b\b ,");
while (ptr2 != NULL) {
printf("%d->", ptr2->value);
ptr2 = ptr2->next;
}
printf("\b\b \n");
ListNode* k;
k = mergeTwoLists(head1, head2);
printf("输出:");
while (k != NULL) {
printf("%d->", k->value);
k = k->next;
}
printf("\b\b \n");
return 0;
}
VS2019中没用错误和警告。
我加了一行代码,循环输出前试着输出了一下,发现ptr2是nullptr,第二个链表建立失败?第一次调用creat建立的链表可以,不知道为什么第二次不行。