Untitled
unknown
plain_text
2 years ago
1.5 kB
3
Indexable
#include <stdio.h> #include <stdlib.h> struct Node { int data; struct Node* next; }; int main() { struct Node* head = NULL; struct Node* temp; // Insert nodes at the end of the linked list struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = 1; new_node->next = NULL; head = new_node; temp = head; new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = 2; new_node->next = NULL; temp->next = new_node; temp = temp->next; new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = 3; new_node->next = NULL; temp->next = new_node; temp = temp->next; // Print the linked list temp = head; printf("Linked list: "); while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); // Delete the last node temp = head; struct Node* prev = NULL; while (temp->next != NULL) { prev = temp; temp = temp->next; } free(temp); if (prev != NULL) { prev->next = NULL; } else { head = NULL; } // Print the linked list after deletion temp = head; printf("Linked list after deletion: "); while (temp != NULL) { printf("%d ", temp->data); temp = temp->next; } printf("\n"); return 0; }
Editor is loading...