本文提供三种方法合并两个有序(从小到大)的单向链表。合并后保持有序。
#include <stdio.h>
#include <stddef.h>
//
// List definition
//
typedef struct rListNode {
int val;
struct rListNode *next;
}ListNode;
//
// List print
//
void ListPrint(ListNode *l)
{
while(l) {
printf("%d\n", l->val);
l = l->next;
}
}
//
// Insert #n into a sorted list #l
//
ListNode *ListSortInsert(ListNode *l, ListNode *n)
{
if (n == NULL) return l;
if (l == NULL) return n;
ListNode *cur = l;
ListNode *nxt = l->next;
if (n->val < cur->val) {
n->next = cur;
return n;
}
while (nxt != NULL && n->val > nxt->val) {
// printf("i val=%d\n", nxt->val);
cur = nxt;
nxt = nxt->next;
}
cur->next = n;
n->next = nxt;
return l;
}
//
// merge two sorted lists