-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathReverseAlternateNodes.java
50 lines (42 loc) · 1.42 KB
/
ReverseAlternateNodes.java
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
/*https://practice.geeksforgeeks.org/problems/given-a-linked-list-reverse-alternate-nodes-and-append-at-the-end/*/
class Solution
{
public static void rearrange(Node odd)
{
Node temp = odd, tail = odd, reverseList = new Node(1), reverseTail = reverseList;
//detach the alternate nodes
while (temp != null && temp.next != null)
{
reverseTail.next = temp.next;
tail = temp;
temp.next = temp.next.next;
reverseTail = reverseTail.next;
reverseTail.next = null;
temp = temp.next;
}
reverseList = reverseList.next;
reverseList = reverseLinkedList(reverseList); //call reverse list function
if (tail.next != null) tail = tail.next; //move tail
tail.next = reverseList; //attach
}
public static Node reverseLinkedList(Node head) {
//edge case
if (head == null || head.next == null)
return head;
//recursion call
head = reverse(head);
return head;
}
public static Node reverse(Node head) {
//last node will be the base case, return it as it is
if (head.next == null)
return head;
/*recursion*/
Node newHead = reverse(head.next);
//reverse
head.next.next = head;
head.next = null;
//return
return newHead;
}
}