Repository navigation
Expand file tree
/
Copy pathnode structure
More file actions
65 lines (55 loc) · 1.41 KB
/
Copy pathnode structure
File metadata and controls
65 lines (55 loc) · 1.41 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
#include <stdio.h>
#include <stdlib.h>
// Define the node structure
struct node {
int data;
struct node *next;
};
struct node *head = NULL;
// Function to insert a node at the beginning
void insert_at_beginning(int data) {
struct node *newnode, *temp;
// Corrected malloc syntax: sizeof(struct node)
newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = data;
if (head == NULL) {
// If list is empty, node points to itself
newnode->next = newnode;
head = newnode;
} else {
temp = head;
// Traverse to the last node
while (temp->next != head) {
temp = temp->next;
}
// Link new node to current head
newnode->next = head;
// Last node now points to the new first node
temp->next = newnode;
// Update head to the new node
head = newnode;
}
printf("Inserted %d at the beginning.\n", data);
}
// Function to display the list
void display() {
struct node *temp;
if (head == NULL) {
printf("List is empty.\n");
return;
}
temp = head;
printf("Circular List: ");
do {
printf("%d -> ", temp->data);
temp = temp->next;
} while (temp != head);
printf("(head)\n");
}
int main() {
insert_at_beginning(30);
insert_at_beginning(20);
insert_at_beginning(10);
display();
return 0;
}