//单链表,上课写的,比较简单的操作。链表的创建,删除,插入,查找元素,遍历的简单操作。2017-3-7
#include<stdio.h> #include<stdlib.h> #define OK 1 #define ERROR 0 typedef int ElemType; typedef int Status; typedef struct LNode { ElemType data; struct LNode *next; }LNode,*LinkList; //函数定义........................................................ LinkList CreatList(int n); void ShowNumber(LinkList haed); Status GetElem(LinkList L,int i,ElemType &e); Status ListInsert(LinkList &L,int i,ElemType e); Status NumbersLen(LinkList L); //实现部分........................................................ LinkList CreatList(int n) { LinkList p,q; LinkList head; head = (LinkList)malloc(sizeof(LNode)); head->next = NULL; q = head; printf("请输入数据\n"); for(int i=0;i<n;i++) { p = (LinkList)malloc(sizeof(LNode)); p->next=NULL; scanf("%d",&p->data); q->next = p; q=q->next; } return head; } void ShowNumber(LinkList head) { LinkList p; p = head->next; printf("输出所有数据:\n"); while(p) { printf("%-4d",p->data); p=p->next; } printf("\n"); } 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 LinkInsert(LinkList &L,int i,ElemType e) { LinkList p; LinkList q; p = L->next; int j=1; while(p && j<i-1) { p = p->next; j++; } if(!p || j>i) return ERROR; q = (LinkList)malloc(sizeof(LNode)); q->data = e; q->next = p->next; p->next = q; return OK; } Status NumbersLen(LinkList L) { LinkList p; int count = 0; p = L->next; while(p) { count++; p=p->next; } if(count) { printf("链表的长度为:%d\n",count); return OK;} else { printf("链表为空!\n"); return ERROR; } } //驱动函数.................................................................. int main() { int n; int e; int i; // int count; LinkList head; printf("输入元素个数:\n"); scanf("%d",&n); head =CreatList(n); ShowNumber(head); printf("请输入查找第几个元素:\n"); scanf("%d",&i); GetElem(head,i,e); printf("查找的元素是: %d\n",e); printf("请输入在第几个元素前插入元素:\n"); scanf("%d",&i); printf("请输入插入的元素:\n"); scanf("%d",&e); if(LinkInsert(head,i,e)) printf("插入成功\n"); else printf("插入失败\n"); ShowNumber(head); NumbersLen(head); return 0; }
数据结构C——单链表
最新推荐文章于 2024-09-23 14:50:51 发布