-
Notifications
You must be signed in to change notification settings - Fork 0
/
stacklinkedlist.c
65 lines (64 loc) · 1.35 KB
/
stacklinkedlist.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
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head=NULL;
void addFirst(int val){
struct node *newNode=malloc(sizeof(struct node));
newNode->data=val;
newNode->next=head;
head=newNode;
}
void addLast(int val){
struct node *newNode=malloc(sizeof(struct node));
newNode->data=val;
newNode->next=NULL;
if(head==NULL){
head=newNode;
}
else{
struct node *lastNode=head;
while(lastNode->next!=NULL){
lastNode=lastNode->next;
}
lastNode->next=newNode;
}
}
struct node *deleteFirst(struct node *head){
if(head==NULL)
return NULL;
struct node *temp=head;
head=temp->next;
free(temp);
return head;
}
struct node *deleteLast(struct node *head){
if(head==NULL)
return NULL;
if(head->next ==NULL){
free(head);
return NULL;
}
struct node *secondLast=head;
while(secondLast->next->next!=NULL)
secondLast=secondLast->next;
free(secondLast->next);
secondLast->next=NULL;
return head;
}
void printList(struct node* head){
struct node *temp=head;
while(temp!=NULL){
printf("%d\n",temp->data);
temp=temp->next;
}
}
int main(){
addLast(10);
addLast(20);
addLast(30);
deleteLast(head);
printList(head);
}