node *p;
p = new node;
p = (node*) malloc (size(node));
- 动态分配函数,C语言里是malloc,C++里是new;
- 单链表--顺序建表
#include<bits/stdc++.h> using namespace std; struct node{ int data; node *next; }; node* creat(int n) //顺序建表 { node *head, *tail, *p; //顺序建表需要头指针和尾指针 head = new node; head->next = NULL; //头指针先指向空,同时把尾放在头的位置 tail = head; for(int i = 0 ; i < n ; i++ ) { p = new node; //为即将进入链表的新的数字申请空间!! scanf("%d",&p->data); p->next = tail->next; //新结点指向尾的下一个,一条链 尾结点指向新结点,两条链 tail->next = p; tail = tail->next; //新插入的节点成为新的尾结点 } return head; } int main () { int n; scanf("%d",&n); node *q = creat(n); //返回的头结点的地址,没有实际储存值 q = q->next; //q的next就是第一个有实际值得 while(q) { if(q->next !=NULL) printf("%d ",q->data); else printf("%d\n",q->data); q = q->next; //改变条件句,否则会死循环 } return 0; }
- 单链表--逆序建表
node *nicreat(int n) //逆序建表 { node *p , *head; //只需要头指针和一个游走指针 head = new node; head->next = NULL; for(int i = 0 ; i < n ; i++ ) { p = new node; //分配空间 scanf("%d",&p->data ); p->next = head->next; //新结点一直在head的后面,所以是逆序的 head->next = p; //两条链!! } return head; }
- 链表的插入即分为 头插和尾插 ,视情况而定。(3.分清楚是在头前尾后还是中间插入)
//头前 p->next = head->next; head->next = p; //尾后 p->next = tail->next; tail->next = p; tail = tail->next; //中间 if(t==ask) { (xin)p->next = q->next; q->next = p; }
- 结点的删除
//双指针,方便操作 设 p 的next为要删除的结点 q = p->next;; p->next = q->next; free(q);
- 链表的逆置
- 链表的归并
//两个有序链表归并,暂定一个是尾 动指针,另一个就动指针,然后比较,直到第二行的数大于了动指针的数,就把它插到尾和动指针之间 head1 = creat(m); head2 = creat(n); p = head1 ->next; q = head2 ->next; tail = head1; while (p&&q) { if(p->val<=q->val) { tail -> next = p; tail = p; p = p ->next; } else { tail -> next = q; tail = q; q = q ->next; } } if (p) { tail->next = p; } else tail->next = q;
- 双链表
node* creat(int n) { Node *head , *q ,*p; int i; head = new node; head->pre = NULL; q = head; for ( i = 0 ; i < n ; i++ ) { p = new node; scanf("%d",&p->data); p->pre = q; q->next = p; q = p; } q->next = NULL; return head; }
- 约瑟夫问题和不敢死队为可循环链表,略。
-
仅供自己复习使用,有错误请见谅。