List有序不交叉链表合并
思路清晰,代码自然就美,题目不难。
告诫自己一点,写代码时候脑袋一定要安静,要想清楚。
犯小错误纯粹是瞎折腾,浪费宝贵时间。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream>
2 using namespace std;
3
4 template<class Type> class List
5 {
6 private:
7 template<class T> class LinkNode
8 {
9 public:
10 LinkNode<Type> *link;
11 Type data;
12
13 LinkNode(LinkNode<Type>* ptr=NULL)
14 {
15 link=ptr;
16 }
17 LinkNode(const Type& item,LinkNode<Type>* ptr=NULL)
18 {
19 data=item;
20 link=ptr;
21 }
22 };
23 LinkNode<Type>* first;
24
25 public:
26 List()
27 {
28 first=new LinkNode<Type>;
29 }
30
31 void input(const Type& end)
32 {
33 LinkNode<Type>* curr;
34 Type val;
35 curr=first;
36 cin>>val;
37 while(val!=end)
38 {
39 LinkNode<Type>* newNode=new LinkNode<Type>(val);
40 curr->link=newNode;
41 curr=curr->link;
42 cin>>val;
43 }
44 }
45
46 void output()
47 {
48 LinkNode<Type>* curr;
49 curr=first;
50 while(curr->link!=NULL)
51 {
52 cout<<curr->link->data<<"";
53 curr=curr->link;
54 }
55 cout<<endl;
56 }
57
58 LinkNode<Type>* getHead() const
59 {
60 return first;
61 }
62
63 void mergeNoIntersectList(const List<Type>& list)
64 {
65 LinkNode<Type> *curr1,*curr2,*curr;
66 curr1=first;
67 curr2=list.getHead()->link; //注意如果getHead()函数不注明是const函数的话那么const对象不能调用非const成员函数
68 while(curr2!=NULL)
69 {
70 if(curr1->link==NULL) //要插入时一定要从curr1->link判断,用curr判断不行
71 {
72 curr1->link=curr2;
73 return;
74 }
75 if(curr2->data<curr1->link->data)
76 {
77 LinkNode<Type> *newNode=new LinkNode<Type>(curr2->data);
78 curr=curr1->link;
79 curr1->link=newNode;
80 curr1->link->link=curr;
81 curr2=curr2->link;
82 }
83 curr1=curr1->link;
84 }
85 }
86 };
87
88 int main()
89 {
90 List<int> list1,list2;
91 list1.input(-1);
92 list2.input(-1);
93 list1.output();
94 list2.output();
95 list1.mergeNoIntersectList(list2);
96 list1.output();
97
98 }