-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathremove nth element.java
More file actions
115 lines (98 loc) · 2.66 KB
/
Copy pathremove nth element.java
File metadata and controls
115 lines (98 loc) · 2.66 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
Uppgift 5 - Remove Nth element
class Uppgift5
{
// Structure of node
static class Node
{
int data;
Node next;
};
// Function to insert node in a linked list
static Node create(Node head, int x) {
Node temp, ptr = head;
temp = new Node();
temp.data = x;
temp.next = null;
if (head == null){
head = temp;
display(head);
}
else{
while (ptr.next != null)
{
ptr = ptr.next;
}
ptr.next = temp;
display(head);
}
return head;
}
// Function to remove nth node from last
static Node removeNthFromEnd(Node head, int B)
{
// To store length of the linked list
int len = 0;
Node tmp = head;
while (tmp != null)
{
len++;
tmp = tmp.next;
}
// B > length, then we can't remove node
if (B > len)
{
System.out.print("Length of the linked list is " + len);
System.out.print(" we can't remove "+ B +
"th node from the");
System.out.print(" linked list\n");
return head;
}
// We need to remove head node
else if (B == len)
{
// Return head.next
System.out.println("removing first element");
return head.next;
}
else
{
// Remove len - B th node from starting
int diff = len - B;
Node prev= null;
Node curr = head;
for(int i = 0; i < diff; i++)
{
prev = curr;
curr = curr.next;
}
prev.next = curr.next;
return head;
}
}
// This function prints contents of linked
// list starting from the given node
static void display(Node head)
{
Node temp = head;
while (temp != null)
{
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
// Driver code
public static void main(String[] args)
{
Node head = null;
head = create(head, 1);
head = create(head, 2);
head = create(head, 3);
head = create(head, 4);
System.out.print("Linked list before modification: \n");
display(head);
head = removeNthFromEnd(head, 3);
System.out.print("Linked list after modification: \n");
display(head);
}
}