c-programming:linked-list:start
فهرست مندرجات
Linked List
Push
// push.c - push() implementation // gcc -std=c99 -Wall -Wextra -Werror -pedantic -o push push.c // headp : head pointer // headpr : head pointer reference #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; void push(struct node **headpr, int n) { struct node *newnode = malloc(sizeof(struct node)); newnode->data = n; newnode->next = *headpr; *headpr = newnode; } int main() { struct node *headp = NULL; push(&headp, 1); push(&headp, 2); push(&headp, 3); push(&headp, 4); push(&headp, 5); for (struct node *p = headp; p != NULL; p = p->next) printf("%d\n", p->data); return 0; }
5 4 3 2 1
Append
// append.c - append() implementation // gcc -std=c99 -Wall -Wextra -Werror -pedantic -o append append.c // headp : head pointer // headpr : head pointer reference #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; void append(struct node **headpr, int n) { struct node *newnode = malloc(sizeof(struct node)); newnode->data = n; newnode->next = NULL; if (*headpr == NULL) { *headpr = newnode; return; } struct node *tailp; tailp = *headpr; while (tailp->next != NULL) tailp = tailp->next; tailp->next = newnode; } int main() { struct node *headp = NULL; append(&headp, 1); append(&headp, 2); append(&headp, 3); append(&headp, 4); append(&headp, 5); for (struct node *p = headp; p != NULL; p = p->next) printf("%d\n", p->data); return 0; }
1 2 3 4 5
Append using Push
// append-push.c - append() implementation using push() // gcc -std=c99 -Wall -Wextra -Werror -pedantic -o append-push append-push.c // headp : head pointer // headpr : head pointer reference #include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; void push(struct node **headpr, int n) { struct node *newnode = malloc(sizeof(struct node)); newnode->data = n; newnode->next = *headpr; *headpr = newnode; } void append(struct node **headpr, int n) { if (*headpr == NULL) { push(headpr, n); return; } struct node *tail; tail = *headpr; while (tail->next != NULL) tail = tail->next; push(&(tail->next), n); } int main() { struct node *headp = NULL; push(&headp, 1); push(&headp, 2); push(&headp, 3); push(&headp, 4); append(&headp, 5); append(&headp, 6); append(&headp, 7); append(&headp, 8); for (struct node *p = headp; p != NULL; p = p->next) printf("%d\n", p->data); return 0; }
4 3 2 1 5 6 7 8
c-programming/linked-list/start.txt · آخرین ویرایش: 2024/06/19 00:09 توسط pejman
