链表是一个很重要的数据结构,一直没有好好的写过练习,这次放假,
好好练习一下。
1、定义链表节点
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef struct Int_Node {
int data; //数据
struct Int_Node * next; //指向下一个节点
}Node;
2、合并两个有序链表
//版本1
Node* Merge(Node *p, Node *q){
Node *head, *tmp;
assert(p && q);
if(p->data <= q->data){
head = tmp = p;
p = p->next;
}else{
head = tmp = q;
q = q->next;
}
while(p && q){
if(p->data <= q->data){
tmp->next = p;
tmp = p;
p = p->next;
}else{
tmp->next = q;
tmp = q;
q = q->next;
}
}
if(p){
tmp->next = p;
}
if(q){
tmp->next = q;
}
return head;
}
//版本2
Node* Merge2(Node *p, Node *q){
Node *head = NULL,
*tmp = NULL,
*cur = NULL;
while(p && q){
if(p->data <= q->data){
cur = p;
p = p->next;
}else{
cur = q;
q = q->next;
}
if(NULL == head){
head = tmp = cur;
}else{
tmp->next = cur;
tmp = cur;
}
}
if(NULL == p){
tmp->next = q;
}else{
tmp->next = p;
}
return head;
}