1
+ // C++ program to delete a node
2
+ #include < bits/stdc++.h>
3
+ using namespace std ;
4
+
5
+ /* Link list node */
6
+ struct Node {
7
+ int data;
8
+ struct Node * next;
9
+ };
10
+
11
+ // Fucntion to delete the node without head
12
+ void deleteNodeWithoutHead (struct Node * pos)
13
+ {
14
+ if (pos == NULL ) // If linked list is empty
15
+ return ;
16
+ else {
17
+
18
+ if (pos->next == NULL ) {
19
+ printf (" This is last node, require head, can't be freed\n " );
20
+ return ;
21
+ }
22
+
23
+ struct Node * temp = pos->next ;
24
+
25
+ // Copy data of the next node to current node
26
+ pos->data = pos->next ->data ;
27
+
28
+ // Perform conventional deletion
29
+ pos->next = pos->next ->next ;
30
+
31
+ free (temp);
32
+ }
33
+ }
34
+
35
+ // Function to print the linked list
36
+ void print (Node* head)
37
+ {
38
+ Node* temp = head;
39
+ while (temp) {
40
+ cout << temp->data << " -> " ;
41
+ temp = temp->next ;
42
+ }
43
+
44
+ cout << " NULL" ;
45
+ }
46
+
47
+ void push (struct Node ** head_ref, int new_data)
48
+ {
49
+ /* allocate node */
50
+ struct Node * new_node = new Node ();
51
+
52
+ /* put in the data */
53
+ new_node->data = new_data;
54
+
55
+ /* link the old list off the new node */
56
+ new_node->next = (*head_ref);
57
+
58
+ /* move the head to point to the new node */
59
+ (*head_ref) = new_node;
60
+ }
61
+
62
+ // Driver Code
63
+ int main ()
64
+ {
65
+ /* Start with the empty list */
66
+ struct Node * head = NULL ;
67
+
68
+ // create linked 35->15->4->20
69
+ push (&head, 20 );
70
+ push (&head, 4 );
71
+ push (&head, 15 );
72
+ push (&head, 35 );
73
+ cout << " Initial Linked List: \n " ;
74
+ print (head);
75
+ cout << endl
76
+ << endl;
77
+
78
+ // Delete 15 without sending head
79
+ Node* del = head->next ;
80
+ deleteNodeWithoutHead (del);
81
+
82
+ // Print the final linked list
83
+ cout << " Final Linked List after deletion of 15:\n " ;
84
+ print (head);
85
+
86
+ return 0 ;
87
+
88
+ // This code has been contributed by Subrat Kumar Swian
89
+ }
0 commit comments