链表的基本操作
有头节点的尾插单链表
先建头节点,头节点没有存放数据,尾插是从左往右
需要3个结构指针
#include
#include typedef struct Node { int x; struct Node* next; }node; int main() { node* head; node* p; node*q; head = (Node *)malloc(sizeof(node)); head->next = NULL; p = head; int t; for (t = 1; t <= 5; t++) { q = (Node*)malloc(sizeof(Node)); printf("input %dnumber'price", t); scanf("%d", &q->x); p->next = q; p = q; } p->next = NULL; return 0; }
带头指针的头插法
从右往左开始输入插入,一样头指针没有存放数据,
若要按正序的,一样也需要3个结构指针
#include
//head cut #include typedef struct Node { int x; struct node* next; }node; int main() { node* head, * p; head = (node*)malloc(sizeof(node)); head->next = NULL; int t = 0; for (t = 1; t <= 5; t++) { p = (node*)malloc(sizeof(node)); printf("this %dnumbook's price is ", t); scanf("%d", &p->x); p->next = head->next; head->next = p; } while (p != NULL) { printf("%d", p->x); p = p->next; } return 0; }