单链表基本操作实现:C语言代码示例及详解
#include <stdio.h> #include <stdlib.h>
#define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define INFEASIBLE -1 #define OVERFLOW -2
typedef int ElemType; typedef int Status;
struct LNode { ElemType data; struct LNode *next; };
ttypedef struct LNode LNode,*LinkList;
Status CreateList_L(LinkList *L,int n) { int i; LinkList p; *L=(LinkList)malloc(sizeof(LNode)); (*L)->next=NULL; printf("请输入%d个数:\n",n); for (i=n;i>0;--i) { p=(LinkList)malloc(sizeof(LNode)); scanf("%d",&p->data); p->next = (*L)->next; (*L)->next = p; } return OK; }
Status ListLength(LinkList L) { LinkList p =(LinkList)malloc(sizeof(LNode)); int j = 1; p = L->next; while(p->next) { p = p->next; j++; } return j; }
Status ListInsert(LinkList *L, int i, ElemType e) { LNode *p,*s; int j = 1; p = (*L)->next; while(p && j < i) { p = p->next; j++; } if (!p || j > i) return ERROR; s = (LinkList)malloc(sizeof(LNode)); s->data = e; s->next = p->next; p->next = s; return OK; }
Status GetElem(LinkList L,int i,ElemType *e) { LinkList p; int j = 1; p = L->next; while(p && j < i) { p = p->next; j++; } if (!p || j > i) return ERROR; *e = p->data; return OK; }
Status DestroyList(LinkList *L) { free(*L); }
Status PrintList(LinkList L) { LinkList p =(LinkList)malloc(sizeof(LNode)); printf("\n"); p = L->next; while(p) { printf("%d\t",p->data); p = p->next; } }
int main() { LinkList L; ElemType x,e; int i,n = 5,choice,position,flag; CreateList_L(&L,n); PrintList(L); printf("\n请输入你要插入结点的位置:"); scanf("%d",&position); printf("请输入你要插入的数据:"); scanf("%d",&x); flag = ListInsert(&L, position,x); if(flag) printf("元素插入成功"); else printf("元素插入失败"); PrintList(L); DestroyList(&L); return 0; }
原文地址: https://www.cveoy.top/t/topic/pcDd 著作权归作者所有。请勿转载和采集!