一个链表的值 赋值给 另一个链表,但是失败
L1链表的值L1->Data赋值到一个新的内存空间p->Data,但是失败了,不懂为啥?如下图
源代码如下
程序代码:
#include <stdio.h> #include <stdlib.h> typedef int ElementType; typedef struct Node *PtrToNode; struct Node { ElementType Data; PtrToNode Next; }; typedef PtrToNode List; List Read(); /* 细节在此不表 */ void Print( List L ); /* 细节在此不表;空链表将输出NULL */ List Merge( List L1, List L2 ); int main() { List L1, L2, L; L1 = Read(); L2 = Read(); L = Merge(L1, L2); Print(L); Print(L1); Print(L2); return 0; } /* 你的代码将被嵌在这里 */ List Read() { PtrToNode first = NULL; int n; printf("Enter a series of integers (0 to terminate): "); scanf("%d", &n); if (n == 0) return first; PtrToNode new_node = malloc(sizeof(struct Node)); if (new_node == NULL) { printf("Error: malloc failed in add to list\n"); exit(0); } new_node->Data = n; new_node->Next = first; first = new_node; for (;;) { printf("Enter a series of integers (0 to terminate): "); scanf("%d", &n); if (n == 0) return first; PtrToNode new_node = malloc(sizeof(struct Node)); if (new_node == NULL) { printf("Error: malloc failed in add to list\n"); exit(0); } new_node->Data = n; for (PtrToNode p1 = first, p2 = NULL; ; p2 = p1, p1 = p1->Next) { if (p2 == NULL &&new_node->Data <= p1->Data) { new_node->Next = p1; first = new_node; break; } if (new_node->Data<=p1->Data && new_node->Data>p2->Data) { new_node->Next = p1; p2->Next = new_node; break; } if(p1->Next==NULL&& new_node->Data>p1->Data) { new_node->Next = p1->Next; p1->Next = new_node; break; } } } } void Print(List L) { if (L == NULL) printf("NULL\n"); else { for (; L != NULL; L = L->Next) printf("%d ", L ->Data); printf("\n"); } } List Merge(List L1, List L2) { PtrToNode first = NULL; PtrToNode t; PtrToNode p = malloc(sizeof(struct Node)); if (p == NULL) { printf("Error: malloc failed in add to list\n"); exit(0); } p->Next = first; first = p; for (;; ) { if (L1 != NULL&&L2 != NULL) if (L1->Data < L2->Data) { p->Data = L1->Data; // 问题出在这种地方 t = L1; L1 = L1->Next; free(t); t = p; } else { p->Data = L2->Data; t = L2; L2 = L2->Next; free(t); t = p; } if (L1 == NULL&&L2 != NULL) { p->Data = L2->Data; t = L2; L2 = L2->Next; free(t); t = p; } if (L2 == NULL&&L1 != NULL) { p->Data = L1->Data; t = L1; L1 = L1->Next; free(t); t = p; } if (L1 == NULL && L2 == NULL) { p->Next = NULL; return first; } PtrToNode p = malloc(sizeof(struct Node)); if (p == NULL) { printf("Error: malloc failed in add to list\n"); exit(0); } t->Next = p; } }
[此贴子已经被作者于2017-9-19 21:08编辑过]