-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patha_117_LinkedList.java
More file actions
102 lines (84 loc) · 2.32 KB
/
a_117_LinkedList.java
File metadata and controls
102 lines (84 loc) · 2.32 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
public class a_117_LinkedList {
public static class Node{
int data ;
Node next ;
public Node(int data){
this.data = data ;
this.next = null ;
}
}
public static Node head ;
public static Node tail ;
public static int size ;
public void addLast(int data){
// step 1: create a node
Node newNode = new Node(data) ;
size ++ ;
if(head == null){
head = tail = newNode ;
return ;
}
// step 2: tail.next = newNode
tail.next = newNode ; // link
// step 3: tail = newNode
tail = newNode ;
}
public void print(){
if(head == null){
System.out.println("Empty Linked List ");
return ;
}
Node temp = head ;
while(temp != null){
System.out.print(temp.data + "->");
temp = temp.next ;
}
System.out.println("null");
}
public void reverse (){
Node prev = null ;
Node curr = tail = head ;
Node next ;
while(curr != null){
next = curr.next ;
curr.next = prev ; // reverse steps
prev = curr ; // Updatation of prev and curr variables
curr = next ;
}
head = prev ;
}
public void deleteNthfromEnd(int n){
// Calculating size
int sz = 0;
Node temp = head ;
while(temp != null){
temp = temp.next ;
sz++ ;
}
if(sz == n){
head = head.next ; // remove first
return ;
}
// sz - n ;
int i = 1;
int iToFind = sz - n ; // Finding deletes index
Node prev = head ;
while(i < iToFind){
prev = prev.next ;
i++ ;
}
prev.next = prev.next.next ;
return ;
}
public static void main(String[] args) {
a_117_LinkedList ll = new a_117_LinkedList() ;
ll.addLast(1);
ll.addLast(2);
ll.addLast(3);
ll.addLast(4);
ll.addLast(5);
ll.print();
ll.deleteNthfromEnd(5);
ll.print();
}
}