1
+ /* *************************************************
2
+
3
+
4
+ Delete a Node from linked list without head pointer
5
+
6
+ Input: 1->2->3->4->5
7
+
8
+ Output: 1->2->4->5 //if 3 is to be deleted
9
+
10
+ ***************************************************/
11
+
12
+ // Deleting a node where head pointer is given is very easy, however,
13
+ // here we don't have the head pointer and only have the pointer of the node which we want to delete.
14
+
15
+ // A simple approach would be to have a ptr node that points to the pointer next to deleted node
16
+ // All you have to do is copy the ptr data into deleted node's data
17
+ // And do some manipulation with both the pointers.
18
+
19
+
20
+ // SOLUTION (in C++):
21
+
22
+ #include < bits/stdc++.h>
23
+
24
+ using namespace std ;
25
+
26
+ struct Node {
27
+ int data;
28
+ struct Node *next;
29
+ Node (int x){
30
+ data = x;
31
+ next = NULL ;
32
+ }
33
+ }*head = NULL , *ptr = NULL , *temp = NULL ;
34
+
35
+ void create (int value)
36
+ {
37
+ if (head == NULL )
38
+ {
39
+ head = new Node (value);
40
+ temp = head;
41
+ }
42
+ else
43
+ {
44
+ temp->next = new Node (value);
45
+ temp = temp->next ;
46
+ temp->next = NULL ;
47
+ }
48
+ }
49
+
50
+ Node *find_node (struct Node *p, int value)
51
+ {
52
+ while (p!=NULL && p->data != value){
53
+ p = p->next ;
54
+ }
55
+ return p;
56
+ }
57
+
58
+ void deleteNodeWithoutHead (struct Node *del)
59
+ {
60
+ if (del == NULL ){ // linked list is empty
61
+ return ;
62
+ }
63
+ if (del->next == NULL ){
64
+ cout<<" The last node requires head, so it can't be freed" <<endl;
65
+ return ;
66
+ }
67
+ ptr = del->next ; // eg: 1->2->3->4->5 suppose del pointer is 3, so,
68
+ // so ptr pointer oints to 4
69
+ // now, acc to the code, 1->2->4->4->5
70
+ // where the second 4 is ptr after free(ptr), we get,
71
+ // 1->2->4->5;
72
+ del->data = del->next ->data ;
73
+ del->next = del->next ->next ;
74
+ ptr->next = NULL ;
75
+ free (ptr);
76
+ }
77
+
78
+ void print (struct Node *node)
79
+ {
80
+ while (node!=NULL )
81
+ {
82
+ cout<<node->data <<" " ;
83
+ node = node->next ;
84
+ }
85
+ }
86
+
87
+ int main ()
88
+ {
89
+ int n, i, k, data;
90
+ cout<<" Enter n" <<endl;
91
+ cin>>n;
92
+ cout<<" Create a linked list" <<endl;
93
+ for (i = 0 ;i<n;i++)
94
+ {
95
+ cin>>data;
96
+ create (data);
97
+ }
98
+ cout<<" Enter the value where you want your delete pointer to be" <<endl;
99
+ cin>>k;
100
+ // Delete k without sending head
101
+ Node* del = find_node (head, k);
102
+ deleteNodeWithoutHead (del);
103
+
104
+ // Print the final linked list
105
+ cout<<" Final Linked List after deletion:\n " ;
106
+ print (head);
107
+
108
+ return 0 ;
109
+
110
+ }
0 commit comments