-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinklist.cpp
More file actions
132 lines (107 loc) · 2.26 KB
/
linklist.cpp
File metadata and controls
132 lines (107 loc) · 2.26 KB
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include<iostream>
using namespace std;
class ListNode{
public:
int val;
ListNode* next;
ListNode(int val){
this->val = val;
this->next = NULL;
}
};
void inserthead(ListNode*& head, int val){
ListNode* n = new ListNode(val);
n->next = head;
head = n;
}
void deleteAthead(ListNode*& head){
if(head == NULL){
return;
}
ListNode* temp = head;
head = head->next;
delete temp;
}
int findLength(ListNode* head){
int cnt = 0;
while(head != NULL){
cnt++;
head = head->next;
}
return cnt;
}
int findLengthRecursive(ListNode* head){
if(head == NULL){
return 0;
}
return 1 + findLengthRecursive(head->next);
}
ListNode* reverseLinkedList(ListNode* head){
ListNode* prev = NULL;
ListNode* curr = head;
while(curr != NULL){
ListNode* temp = curr->next;
curr->next = prev;
prev = curr;
curr = temp;
}
return prev;
}
ListNode* getTail(ListNode* head){
while(head->next != NULL){
head = head->next;
}
return head;
}
void insertTail(ListNode*& head, int val){
if(head == NULL){
head = new ListNode(val);
return;
}
ListNode* tail = getTail(head);
tail->next = new ListNode(val);
}
void deleteAtTail(ListNode*& head){
if(head == NULL){
return;
}
if(head->next == NULL){
deleteAthead(head);
return;
}
ListNode* cur = head;
ListNode* prev = NULL;
while(cur->next != NULL){
prev = cur;
cur = cur->next;
}
prev->next = NULL;
delete cur;
}
void printLinkedlist(ListNode* head){
while(head != NULL){
cout << head->val << " ";
head = head->next;
}
cout << endl;
}
int main(){
ListNode* head = NULL;
inserthead(head, 50);
inserthead(head, 40);
inserthead(head, 30);
inserthead(head, 20);
inserthead(head, 10);
printLinkedlist(head);
deleteAthead(head);
printLinkedlist(head);
cout << findLength(head) << endl;
cout << findLengthRecursive(head) << endl;
head = reverseLinkedList(head);
printLinkedlist(head);
insertTail(head, 60);
printLinkedlist(head);
deleteAtTail(head);
printLinkedlist(head);
return 0;
}