forked from dharmanshu1921/Website-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist_recursion.cpp
More file actions
75 lines (63 loc) · 1.42 KB
/
linkedlist_recursion.cpp
File metadata and controls
75 lines (63 loc) · 1.42 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
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
// Deletes k-th node and returns new header.
Node* deleteNode(Node* start, int k)
{
// If invalid k
if (k < 1)
return start;
// If linked list is empty
if (start == NULL)
return NULL;
// Base case (start needs to be deleted)
if (k == 1)
{
Node *res = start->next;
delete(start);
return res;
}
start->next = deleteNode(start->next, k-1);
return start;
}
/* Utility function to insert a node at the beginning */
void push(struct Node **head_ref, int new_data)
{
struct Node *new_node = new Node;
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
/* Utility function to print a linked list */
void printList(struct Node *head)
{
while (head!=NULL)
{
cout << head->data << " ";
head = head->next;
}
printf("\n");
}
/* Driver program to test above functions */
int main()
{
struct Node *head = NULL;
/* Create following linked list
12->15->10->11->5->6->2->3 */
push(&head,3);
push(&head,2);
push(&head,6);
push(&head,5);
push(&head,11);
push(&head,10);
push(&head,15);
push(&head,12);
int k = 3;
head = deleteNode(head, k);
printf("\nModified Linked List: ");
printList(head);
return 0;
}