-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdelete_last_node.c
95 lines (78 loc) · 1.6 KB
/
delete_last_node.c
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
#include<stdio.h>
struct Node
{
int data;
struct Node *next;
};
struct Node *addToEmpty(struct Node *last, int data)
{
if (last != NULL)
{
return last;
}
struct Node *temp = (struct Node*)malloc(sizeof(struct Node));
temp -> data = data;
last = temp;
last -> next = last;
return last;
}
struct Node *addEnd(struct Node *last, int data)
{
if (last == NULL)
{
return addToEmpty(last, data);
}
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp -> data = data;
temp -> next = last -> next;
last -> next = temp;
last = temp;
return last;
}
void traverse(struct Node *last)
{
struct Node *p;
if (last == NULL)
{
return;
}
p = last->next;
do
{
printf("%d ",p -> data);
p = p -> next;
}
while(p != last);
}
struct Node *solution(struct Node *last) {
//Write your code here
struct Node*p=last;
if(last==NULL){
printf("no element present");
return NULL; }
struct Node*q=last->next;
//using two pointers to ensure that the last node is deleted
do
{
p=p->next;
q=q->next;
}while(q!=last);
p->next=last ;
return last ;
}
//Your program will be evaluated by this main method and several test cases.
int main()
{
int n,x;
scanf("%d",&n);
struct Node *last = NULL;
for(int i = 0; i < n; i++)
{
scanf("%d",&x);
last = addEnd(last,x);
}
scanf("%d",&x);
last = solution(last);
traverse(last);
return 0;
}