-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathreverseListInterative.java
More file actions
36 lines (27 loc) · 886 Bytes
/
reverseListInterative.java
File metadata and controls
36 lines (27 loc) · 886 Bytes
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
public reverseListIteratively (Node head) {
if (head == NULL || head.next == NULL) {
return; //empty or just one node in list
}
Node Second = head.next;
//store third node before we change
Node Third = Second.next;
//Second's next pointer
Second.next = head; //second now points to head
head.next = NULL; //change head pointer to NULL
//only two nodes, which we already reversed
if (Third == NULL) {
return;
}
Node CurrentNode = Third;
Node PreviousNode = Second;
while (CurrentNode != NULL) {
Node NextNode = CurrentNode.next;
CurrentNode.next = PreviousNode;
/* repeat the process, but have to reset
the PreviousNode and CurrentNode
*/
PreviousNode = CurrentNode;
CurrentNode = NextNode;
}
head = PreviousNode; //reset the head node
}