题目要求
本题要求实现一个函数,将两个链表表示的递增整数序列合并为一个非递减的整数序列。
函数原型为
List Merge( List L1, List L2 );
代码
List Merge( List L1, List L2 ){
List p=L1->Next;
List q=L2->Next;
List L=(List)malloc(sizeof(struct Node));//创建头结点
L->Next=NULL;
List k=L;//尾结点
List newnode;//新节点
while(p&&q){
newnode=(List)malloc(sizeof(struct Node));
newnode->Next=NULL;
if(p->Data<=q->Data){
newnode->Data=p->Data;
//q=L1->Next;
p=p->Next;
k->Next=newnode;
k=k->Next;
}
else if(p->Data>q->Data){
newnode->Data=q->Data;
q=q->Next;
k->Next=newnode;
k=k->Next;
}
}
if(p!=NULL) k->Next=p;
if(q!=NULL)k->Next=q;
L1->Next=NULL;
L2->Next=NULL;
return L;
}
复习感悟
复写的时候才注意到不能使用新节点,其实刚开始写的时候也想到了要直接rear->next=q;但是以为这样不行,后来在vs中调试跑了一下,明白了过程,对链表有了更深的了解
题目要求的合并代码:
list merge(list l1, list l2) {
list l3=new Node;
l3->next = NULL;
list rear = l3;
list q = l1->next;
list p = l2->next;
while (q && p) {
if (q->data < p->data) {
rear->next = q;
q = q->next;
rear = rear->next;
}
else {
rear->next = p;
p = p->next;
rear = rear->next;
}
}
if (q) rear->next = q;
if (p) rear->next = p;
l1->next = NULL;
l2->next = NULL;
return l3;
}
总体代码:
#include<iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
typedef Node* list;
list read() {
int n;
cin >> n;
list head=new Node;
head->next = NULL;
list rear = head;
list newnode;
while (n--) {
newnode = new Node;
cin >> newnode->data;
newnode->next = NULL;
rear->next = newnode;
rear = rear->next;
}
return head;
}
void printList(list l) {
list q = l->next;
if (!q) cout << "NULL";
while (q) {
cout << q->data<<" ";
q = q->next;
}
cout << endl;
}
list merge(list l1, list l2) {
list l3=new Node;
l3->next = NULL;
list rear = l3;
list q = l1->next;
list p = l2->next;
while (q && p) {
if (q->data < p->data) {
rear->next = q;
q = q->next;
rear = rear->next;
}
else {
rear->next = p;
p = p->next;
rear = rear->next;
}
}
if (q) rear->next = q;
if (p) rear->next = p;
l1->next = NULL;
l2->next = NULL;
return l3;
}
int main() {
list l1 = read();
list l2 = read();
list l3 = merge(l1, l2);
printList(l3);
printList(l1);
printList(l2);
return 0;
}