-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListNode.cpp
More file actions
146 lines (109 loc) · 2.75 KB
/
LinkedListNode.cpp
File metadata and controls
146 lines (109 loc) · 2.75 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
133
134
135
136
137
138
139
140
141
142
143
144
145
#include "LinkedListNode.h"
extern int (*gPrintFn)( const char * format, ... );
LinkedListNode* Create123_LinkedList()
{
LinkedListNode* head = 0;
Insert_LinkedList(&head, 3);
Insert_LinkedList(&head, 2);
Insert_LinkedList(&head, 1);
return head;
}
unsigned int Length_LinkedList( LinkedListNode* head )
{
LinkedListNode* current = head;
int length = 0;
while (current != 0)
{
length++;
current = current->next;
}
return length;
}
void Insert_LinkedList( LinkedListNode** headRef, int value )
{
LinkedListNode* node = new LinkedListNode();
node->data = value;
node->next = *headRef;
*headRef = node;
gPrintFn("New Element inserted. Head is %d \n", (*headRef)->data);
}
void Print_LinkedList( LinkedListNode* head )
{
LinkedListNode* current = head;
if(current == 0)
{
gPrintFn("List is Empty.");
}
while(current != 0)
{
gPrintFn(" %d ", current->data);
// print slew
if(current->next != 0)
gPrintFn("->");
current = current->next;
}
gPrintFn("\n");
}
void InsertAtTail_LinkedList( LinkedListNode** headRef, int value )
{
LinkedListNode* current = *headRef;
if (current == 0) // special case if Linked list is empty
{
Insert_LinkedList(headRef, value);
}
else
{
while (current->next != 0)
{
current = current->next;
}
Insert_LinkedList(&(current->next), value);
}
}
LinkedListNode* Copy_LinkedList( LinkedListNode* head )
{
LinkedListNode* current = head;
LinkedListNode* newHead = 0;
while (current != 0)
{
InsertAtTail_LinkedList(&newHead, current->data);
current = current->next;
}
return newHead;
}
LinkedListNode* Copy0_LinkedList( LinkedListNode* head )
{
LinkedListNode* current = head;
LinkedListNode* newHead = 0;
LinkedListNode* tail = 0;
while (current != 0)
{
if(newHead == 0)
{
newHead = new LinkedListNode();
newHead->data = current->data;
newHead->next = 0;
tail = newHead;
}
else // add rest of the elements to the tail of list so that elements are not added in reverse
{
tail->next = new LinkedListNode();
tail->next->data = current->data;
tail->next->next = 0;
tail = tail->next;
}
current = current->next;
}
return newHead;
}
LinkedListNode* CopyRecursive_LinkedList( LinkedListNode* head )
{
LinkedListNode* node = 0;
if (head != 0)
{
node = new LinkedListNode();
node->data = head->data;
node->next = CopyRecursive_LinkedList(head->next);
}
return node;
}