#include<stdio.h> #include<stdlib.h> #include<malloc.h> #include<assert.h> typedef struct node { int data; struct node *next; }NODE,*PNODE,*LINKLIST; //初始化 void init(LINKLIST *list) { (*list) = (PNODE) malloc(sizeof(NODE)); (*list) ->next = *list;//头指针指向头结点 } //添加数据, void add(LINKLIST list,int data) { PNODE p=list,q; //先将p移动到最后一个节点 while(p->next != list) { p=p->next; }//end while q=(PNODE)malloc(sizeof(NODE)); q->data = data; q->next = list;//新节点的指针域始终指向头结点 p->next = q; }//end add //删除list中第i个节点 i>=1 void del(LINKLIST list,int i,int *data) { PNODE p=list,q; assert(i>=1 && p); while(--i) { p=p->next; if(p->next==list) break; } assert(i==0);//为i断言,防止删除操作不合法 q=p->next;//q为需要删除的节点 *data = q->data; p->next = q->next; free(q); }//end del //在list中的第i个位置插入节点 void insert(LINKLIST list,int i,int data) { PNODE p=list,q; while(--i && p->next!=list) { p=p->next; } assert(i==0); q = (PNODE)malloc(sizeof(NODE)); q->data =data; q->next = p->next; p->next = q; } //获取链表的第i个位置,i>=1 int getData(LINKLIST list,int i) { PNODE p=list; //将p移动到链表的第i-1个位置 while(--i && p->next!=list) { p=p->next; } assert(i==0); return p->data; } //获取链表的长度 int getLen(LINKLIST list) { PNODE p=list; int len=0; assert(p); while((p=p->next)!=list) len++; return len; } //清空链表 void clear(LINKLIST list) { PNODE p=list,q; assert(p); while(p->next!=list) { q=p->next;//q需要删除 p->next = q->next; free(q); } } //链表销毁 void destory(LINKLIST *list) { PNODE p=*list,q; assert(p); do { q=p->next; free(p); p=q; }while(p!=*list); *list=NULL; } //显示链表 void display(LINKLIST list) { PNODE p=list; while((p=p->next)!=list) printf("%d ",p->data); printf(" "); } int main() { int i,j; LINKLIST list=NULL; init(&list); for(i=1;i<=10;i++) insert(list,i,i); insert(list,11,100); display(list); destory(&list);//销毁链表 system("pause"); return 0; }