-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListMethods.java
More file actions
129 lines (103 loc) · 2.77 KB
/
LinkedListMethods.java
File metadata and controls
129 lines (103 loc) · 2.77 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
import java.io.*;
/*
* Some sections of code may belong to others, most of this is for personal practice/notes purposes
*/
public class LinkedListMethods {
}
//iterative method
//time complexity O(n)
class LinkedList{
static Node head;
static class Node{
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
Node reverse(Node node){
Node prev = null;
Node current = node;
Node next = null;
while(current != null){
next = current.next;
current.next = prev;
prev = current;
current = next;
}
node = prev;
return node;
}
void printList(Node node){
while(node != null){
System.out.print(node.data + " ");
node = node.next;
}
}
public static void main(String[] args){
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(15);
list.head.next.next = new Node(4);
list.head.next.next.next = new Node(20);
System.out.println("Given linked list");
list.printList(head);
head = list.reverse(head);
System.out.println("");
System.out.println("Reversed linked list ");
list.printList(head);
}
}
//reverse a linked list using recursion
//divide list in two parts - first node and rest of list
class recursion {
static Node head;
static class Node {
int data;
Node next;
Node(int d){
data = d;
next = null;
}
}
static Node reverse (Node head){
if(head == null || head.next == null){
return head;
}
//reverse the rest list and put the first element at the end
Node rest = reverse(head.next);
//head is currently the last node before the final node aka rest
//so head.next.next is the node after last
//set node after last equal to node before last
head.next.next = head;
//gets rid of the pointerß
head.next = null;
//fix head pointer
return rest;
}
static void print(){
Node temp = head;
while (temp != null){
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
static void push(int data){
Node temp = new Node(data);
temp.next = head;
head = temp;
}
public static void main(String args[]){
push(20);
push(4);
push(15);
push(85);
System.out.println ("Given linked list");
print();
head = reverse(head);
System.out.println("Reversed linked list");
print();
}
}