标签:
#include <stdio.h> #include <stdlib.h> #include <unistd.h> typedef struct node { int data; struct node *next; } node; node *LinkList; void display(node *list); node *insert(node *list, int data); void main() { LinkList = insert(LinkList, 1); display(LinkList); LinkList = insert(LinkList, 2); display(LinkList); } node* create(node *list) { list = (node *)malloc(sizeof(node)); return list; } void display(node *list) { while(list) { printf("address:%d, data: %d, its next: %d\n", list, list->data, list->next); list = list->next; } } node* insert(node *list, int data) { node* head = list; /* If the list is empty*/ if(list==NULL) { list = (node *)malloc(sizeof(node)); list->data = data; list->next = NULL; head = list; return head; }
/* Iterate through the list till we encounter the last node. */ while(list->next != NULL) { list = list->next; } /* Allocate memory for the new node and put data in it */ list->next = (node *)malloc(sizeof(node)); list = list->next; list->data = data; list->next = NULL; return head; }
gcc SinglyLinkList3.c -lcurses -o SinglyLinkList3 ./SinglyLinkList3address:19963920, data: 1, its next: 0 address:19963920, data: 1, its next: 19963952 address:19963952, data: 2, its next: 0
1) Because the code "(node *)malloc(sizeof(node));" will return a node with default value, that‘s why there is no Initialize function implemented.
2) Because C Language doesn‘t support the "&" address-of operator in parameters, so we need to restore the head pointer and return it in Insert function.
3) There will be 2 different operations between empty list and non-empty list.
标签:
原文地址:http://www.cnblogs.com/Aegis-Liang/p/4795280.html