C单链表操作
#include <stdio.h> #include <stdlib.h> #define ElemType int #define Status int #define OK 0 #define ERROR -1 typedef struct { ElemType data; struct Node *next; }Node; typedef struct Node *LinkList; /*定义LinkList*/ Status GetElem(LinkList L, int i, ElemType *e) { int j=1; LinkList p; /*声明一指针p*/ p = L->next; while (p && j<i) { p = p->next; ++j; }; if (i <= j || !p) return ERROR; *e = p->data; return OK; } /*初始条件: 顺序线性表已经存在, 1<=i<=ListLength(L).*/ /*操作结果: 这里指在链表第i个元素之前插入元素e, L的长度加1*/ /*元素前后定义:箭头指向的方向为前*/ Status ListInsert(LinkList L,int i, ElemType e) { LinkList p,s; p = *L; int j=1; while(p && j<i) { p = p->next; ++j; } if(!p || j >= i) return ERROR; /*第i个节点不存在*/ s = (LinkList)malloc(sizeof(Node)); s->data = e; s->next = p->next; p->next = s; return OK; } /*初始条件: 顺序线性表已经存在, 1<=i<=ListLength(L).*/ /*操作结果: 这里指删除链表的第i个元素, 并使用e返回该元素值,L的长度减1*/ Status ListDelete(LinkList L, int i, ElemType *e) { LinkList p, q; p = *L; int j=1 while(p && j<i) { p = p->next; ++j; } if(!p || j >= i) return ERROR; /*第i个节点不存在*/ q = p->next; e = q->data; p->next = q->next; free(q); /*让系统回收次节点,释放内存*/ return OK; } void CreateListHead(LinkList *L, int n) { LinkList *p; int i; srand(time(0)); /*初始化随机数种子*/ *L = (LinkList)malloc(sizeof(Node)); L->next = NULL; /*先建立一个带头节点的单链表*/ for(i=0; i<n; i++) { p = (LinkList)malloc(sizeof(Node)); /*生成新节点*/ p->data = rand()%100+1; p->next = (*L)->next; (*L)->next = p; } } void CreateListTail(LinkList *L, int n) { LinkList *p, r; int i; srand(time(0)); *L = (LinkList)malloc(sizeof(Node)); L->next = NULL; r = *L; /*将链表尾指针赋给r*/ for(i=0; i<n; i++) { p = (LinkList)malloc(sizeof(Node)); /*生成新节点*/ p->data = rand()%100+1; r->next = p; r = p; /*将当前的新节点定义为表尾的终端节点*/ } r->next=NULL; } Status ClearList(LinkList *L) { LinkList p,q; p = (*L)->next; while(p) { q = p->next; free(q); p = q; } (*L)->next = NULL; return OK; } int main() { LinkList *mylist; CreateListTail(mylist, 16); printf(" %d ", mylist->next->data); }
勤苦修行得自在,道力有边边亦无边!