- 结构(带头结点)
- 初始化
- 创建(n个结点)
- 插入
- 删除
- 遍历
- 销毁
判空:(head->next==head)
初始化:主要注意链表为空的条件,执行语句:L->next=L;
void InitList(List &L)/*初始化空表*/ {L=(List)malloc(sizeof(Node));/*生成头结点*/L->next=L;/*判空的条件*/ }
void creat(List &head,int n)/*创建*/ {int e;List p,s;p=head;while(n>0){cin>>e;s=(List)malloc(sizeof(Node));s->data=e;p->next=s;s->next=head;p=s;--n;} }
插入:在第i个位置处插入e,先把指针移到i-1处,然后进行操作。此外,p从头结点开始移动。
void Insert(List &L,int i,int e) {List p,s;p=L;/*p等于头结点*/while(i-1>0)/*移动到第i个位置之前,需要移动i-1次*/{p=p->next;i--;}s=(List)malloc(sizeof(Node));s->data=e;s->next=p->next;p->next=s; }
删除:将第i个元素删除。借助两个游标s,p,将p移动到i位置,s同步移动到i-1处,两者配合操作。p从头结点处开始,需要移动i次!
void Delete(List &L,int i) {List s,p;p=L;while(i>0){s=p;p=p->next;i--;}s->next=p->next;free(p); }
#include <iostream> using namespace std; typedef struct node {int data;struct node *next; }*List,Node;void InitList(List &L)/*初始化空表*/ {L=(List)malloc(sizeof(Node));/*生成头结点*/L->next=L;/*判空的条件*/ } void creat(List &head,int n)/*创建*/ {int e;List p,s;p=head;while(n>0){cin>>e;s=(List)malloc(sizeof(Node));s->data=e;p->next=s;s->next=head;p=s;--n;} } void Traverse(List &head)/*遍历*/ {List p=head->next;while(p!=head){cout<<p->data<<" ";p=p->next;}; } void Destory(List &L)/*销毁*/ {List p,q;p=L->next;while(p!=L){q=p;p=p->next;free(q);}L->next=L; } int main() {List L;InitList(L);creat(L,3);print(L);destory(L);return 0; }