List有序不交叉链表合并

本文分享了一种使用C++模板实现链表的方法,并详细解释了如何将两个不相交的链表进行合并的代码逻辑。强调了清晰的编程思路对于代码质量的重要性,避免小错误造成的效率损失。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

思路清晰,代码自然就美,题目不难。

告诫自己一点,写代码时候脑袋一定要安静,要想清楚。

犯小错误纯粹是瞎折腾,浪费宝贵时间。

 

View Code
 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 }

 

转载于:https://www.cnblogs.com/YipWingTim/archive/2011/11/07/2238670.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值