c - 如何更改输入链表而不返回
问题描述
Q:合并两个链表,返回合并后的List和两个空链表。
输入:
3
1 3 5
5
2 4 6 8 10
期望的输出:
1 2 3 4 5 6 8 10
NULL
NULL
但我得到了:
1 2 3 4 5 6 8 10
1 3 5
2 4 6 8 10
我的代码:
#include <stdio.h>
#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 );
List Merge( List L1, List L2 );
void C(List L);
int main()
{
List L1, L2, L;
L1 = Read();
L2 = Read();
L = Merge(L1, L2);
Print(L);
C(L1);
Print(L1);
Print(L2);
return 0;
}
void C(List L){
L = L->Next;
}
List Merge( List L1, List L2 ){
List prehead = (List)malloc(sizeof(struct Node));
List t = prehead;
while(L1&&L2){
if(L1->Data < L2->Data){
List node = (List)malloc(sizeof(struct Node));
node->Data = L1->Data;
t->Next = node;
t = t->Next;
L1 = L1->Next;
}
else{
List node = (List)malloc(sizeof(struct Node));
node->Data = L2->Data;
t->Next = node;
t = t->Next;
L2 = L2->Next;
}
}
while(L1){
List node = (List)malloc(sizeof(struct Node));
node->Data = L1->Data;
t->Next = node;
t = t->Next;
L1 = L1->Next;
}
while(L2){
List node = (List)malloc(sizeof(struct Node));
node->Data = L2->Data;
t->Next = node;
t = t->Next;
L2 = L2->Next;
}
t->Next = NULL;
return prehead->Next;
}
List Read(){
int n;
scanf("%d",&n);
List prehead = (List)malloc(sizeof(struct Node));
List L = prehead;
if(n==0) return NULL;
for(int i=0; i<n; i++)
{
List node = (List)malloc(sizeof(struct Node));
scanf("%d",&node->Data);
L->Next = node;
L = L->Next;
}
List node = prehead;
List head = prehead->Next;
free(node);
L->Next = NULL;
return head;
}
void Print(List L){
if(!L) printf("NULL");
List p = L;
int flag = 0;
while(p){
if(!flag)
flag = 1;
else
printf(" ");
printf("%d",p->Data);
p = p->Next;
}
printf("\n");
}
一切运作良好。但总的来说,它并没有改变任何东西。
解决方案
推荐阅读
- android - 如何在孩子使用 PanResponder 在其中移动时滚动父 ScrollView
- javascript - 尝试在成功的 ajax 发布后删除类删除 html 元素
- ruby-on-rails - active_storage url_for 产生不可用的 url
- sed - FreeBSD 中的多行删除
- discord - 被踢时审核日志原因显示为 [object Object]
- stored-procedures - 从存储过程执行的密码比原始密码慢得多
- java - 数组成员(Java 数组理论)
- reactjs - 反应原生状态不变
- c# - c# 8 可空性 - 泛型类“知道”它的可空性
- java - 如何检查一个列表的对象是否包含另一个列表的任何对象