酷代码 AI
菜单
服务商

C 语言实现按规则合并单链表:巧用原表空间,含代码与题解

#include<stdio.h> typedef struct Node{ int data; struct Node* next; }Node; // 创建链表 Node* createList(){ Node* head = (Node*)malloc(sizeof(Node)); head->next = NULL; return head; } // 向链表末尾插入元素 void insert(Node* head, int data){ Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; Node* p = head; while(p->next != NULL){ p = p->next; } p->next = newNode; } // 合并两个链表 Node* mergeLists(Node* la, Node* lb){ Node* lc = la; Node* pa = la->next; Node* pb = lb->next; while(pa != NULL && pb != NULL){ lc->next = pa; lc = pa; pa = pa->next; lc->next = pb; lc = pb; pb = pb->next; } if(pa != NULL){ lc->next = pa; } if(pb != NULL){ lc->next = pb; } return la; } // 打印链表的元素 void printList(Node* head){ if(head->next == NULL){ printf("链表为空\n"); return; } Node* p = head->next; while(p != NULL){ printf("%d", p->data); p = p->next; } } int main(){ Node* la = createList(); Node* lb = createList(); int num; scanf("%d", &num); while(num != 1){ insert(la, num); scanf("%d", &num); } scanf("%d", &num); while(num != 1){ insert(lb, num); scanf("%d", &num); } Node* lc = mergeLists(la, lb); printList(lc); return 0; } ######[AI写代码神器 | 1020点数解答 | 2024-06-17 15:01:02]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]