-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedListDelete.java
More file actions
79 lines (61 loc) · 1.62 KB
/
Copy pathLinkedListDelete.java
File metadata and controls
79 lines (61 loc) · 1.62 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
class LinkedList {
Node head;
class Node {
int data;
Node next;
Node {
data = d;
next = NULL;
}
}
/* Deletes the first occurence of key in the Linked LIst*/
void deleteNode (int key) {
//Store the head node
Node temp = head, prev = NULL;
// If the node itself holds the key to be deleted
if(temp != NULL && temp.data == key) {
head = temp.next; //Changed the head
return;
}
//Search the node to be deleted and keep track of previous node as we need to change temp.next
while(temp != NULL && temp.data != key) {
prev = temp;
temp = temp.next;
}
//if key was not present in the list
if(temp == NULL) return;
// Unlink the node from the list
prev.next = temp.next;
}
/* Inserts a new Node at front of the list. */
public void push(int new_data)
{
Node new_node = new Node(new_data);
new_node.next = head;
head = new_node;
}
/* This function prints contents of linked list starting from
the given node */
public void printList()
{
Node tnode = head;
while (tnode != null)
{
System.out.print(tnode.data+" ");
tnode = tnode.next;
}
}
public static void main(String[] args)
{
LinkedList llist = new LinkedList();
llist.push(7);
llist.push(1);
llist.push(3);
llist.push(2);
System.out.println("\nCreated Linked list is:");
llist.printList();
llist.deleteNode(1); // Delete node at position 4
System.out.println("\nLinked List after Deletion at position 4:");
llist.printList();
}
}