题目:有两个有序的单链表,将它们合并为一个有序的单链表,不允许分配额外空间。
分析:
这一道题应该很简单,不分配额外空间是很容易满足的。数据结构课本上就有这样的实现,具体不多说,看参考代码:
1: struct Node
2: {
3: int value;
4: struct Node* next;
5: };
6:
7: Node* mergeLinks(struct Node *head1,struct Node* head2)
8: {
9: if(head1==NULL)
10: return head2;
11: if(head2==NULL)
12: return head1;
13:
14: struct Node *head;
15: if(head1->value > head2->value)
16: {
17: head=head2;
18: head2=head2->next;
19: }
20: else
21: {
22: head=head1;
23: head1=head1->next;
24: }
25: struct Node *current=head;
26: while(head1!=NULL && head2!=NULL)
27: {
28: if(head1->value > head2->value)
29: {
30: current->next=head2;
31: current=head2;
32: head2=head2->next;
33: }
34: else
35: {
36: current->next=head1;
37: current=head1;
38: head1=head1->next;
39:
40: }
41:
42: }
43: if(head1!=NULL)
44: {
45: current->next=head1;
46: }
47: if(head2!=NULL)
48: {
49: current->next=head2;
50: }
51:
52: return head;
53:
54: }