Skip to content

Commit 35d6601

Browse files
authored
Add files via upload
1 parent 1b528b4 commit 35d6601

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
#include <stdio.h>
2+
#include <stdlib.h>
3+
struct Node
4+
{
5+
int data;
6+
struct Node* next;
7+
}*first=NULL;
8+
void Create(int A[], int n)
9+
{
10+
int i;
11+
struct Node* last, * t;
12+
first = (struct Node*)malloc(sizeof(struct Node));
13+
first->data = A[0];
14+
first->next = NULL;
15+
last = first;
16+
17+
for (i = 1; i < n; i++)
18+
{
19+
t = (struct Node*)malloc(sizeof(struct Node));
20+
t->data = A[i];
21+
t->next = NULL;
22+
last->next = t;
23+
last = t;
24+
}
25+
}
26+
void Display(struct Node* p)
27+
{
28+
while (p != NULL)
29+
{
30+
printf("->%d", p->data);
31+
p = p->next;
32+
}
33+
}
34+
int count(struct Node* p) // pointer to 1st node
35+
{
36+
int c = 0; // intially assigning count as zero
37+
while (p != NULL) // when ll is not empty
38+
{
39+
c++; // increase the no of count 1 everytime
40+
p = p->next; // p to next node
41+
}
42+
return c; // return the total nodes in ll
43+
}
44+
45+
46+
int Delete(struct Node* p, int index) // it should take pointer to 1st node & index from which element to be deleted
47+
{
48+
struct Node* q=NULL; // tail pointer
49+
int x = -1, i;
50+
51+
if (index < 1 || index > count(p)) // weather index is valid or not , index is from 1 to length
52+
return -1;
53+
if (index == 1) // special cse if index is on 1st node
54+
{
55+
q = first; // make q points on 1st node
56+
x = first->data; // take the data from 1st node
57+
first = first->next; // move 1st pointer to next node
58+
free(q); // del the previous 1st node
59+
return x;
60+
}
61+
else // if it is not 1st index || any other index
62+
{
63+
for (i = 0; i < index - 1; i++) // using for loop we will move p and q
64+
{
65+
q = p; // everytime q will moved upon p and p will move upon next node
66+
p = p->next;
67+
}
68+
// p will be pointing on node which we want to delete
69+
q->next = p->next; // p will be logically removed from ll
70+
x = p->data; // strote data to be del in x from p-data
71+
free(p); //
72+
return x; // deleted valte
73+
74+
}
75+
76+
77+
}
78+
79+
80+
81+
int main()
82+
{
83+
int A[] = { 10,20,30,40,50 };
84+
Create(A, 5);
85+
86+
printf("The deleted element is %d\n", Delete(first, 5)); // we will pass invalid index it will show -1
87+
Display(first);
88+
printf("\n\n");
89+
90+
return 0;
91+
92+
}

0 commit comments

Comments
 (0)