-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList.cpp
103 lines (95 loc) · 1.83 KB
/
LinkedList.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "LinkedList.h"
template<class T>
LinkedList<T>::~LinkedList<T>()
{
Node<T>* temp;
while (head)
{
temp = head ->link;
delete head;
head = temp;
}
}
template<class T>
bool LinkedList<T>::IsFull()const
{
try
{
Node<T>* temp = new Node<T>;
delete temp;
return false;
}
catch(Invalid)
{
return true;
}
}
template<class T>
int LinkedList<T>::GetLength()const
{
if(IsEmpty())
return 0;
Node<T>* temp = head;
int length = 0;
while (head)
{
length++;
temp = temp -> link;
}
return length;
}
template<class T>
void LinkedList<T>::Destroy()
{
Node<T>* temp;
while (head)
{
temp = head ->link;
delete head;
head = temp;
}
}
template<class T>
T LinkedList<T>::GetHead()const
{
return *head;
}
template<class T>
LinkedList<T>& LinkedList<T>::Insert(const T& x)
{
if(IsEmpty())
{
head = new Node<T>(x);
tail = head;
return this;
}
if(IsFull())
throw Invalid();
Node<T> *temp = new Node<T>(x);
tail -> link = temp;
tail = temp;
return this;
}
template<class T>
LinkedList<T>& LinkedList<T>::Delete(int k, T& x) //删除第k个结点
{
if(!IsEmpty())
{
int cur = 1;
Node<T> *temp = head;
Node<T> *ptemp;
while(cur < k && temp)
{
ptemp = temp;
temp = temp -> link;
cur ++;
}
if(cur < k)
throw Invalid();
ptemp -> link = temp -> link;
delete temp;
return this;
}
return this;
}
//删掉所有值为key的链表结点并在参数中返回删掉的总节点数