单链表的基本操作

来源:互联网 发布:美国为什么强大知乎 编辑:程序博客网 时间:2024/06/06 04:58
#include <stdio.h>#include <stdlib.h># define TRUE 1# define FALSE 0# define OK 1# define ERROR 0typedef int ElemType;typedef int Status;typedef struct LNode{ElemType data;struct LNode *next;}LNode, *LinkList;LinkList CreateList(LinkList &L){L = (LinkList)malloc(sizeof(LinkList));L->next = NULL;//构造空的线性表LNode *p;ElemType e;printf("请输入节点元素值:");scanf_s("%d", &e);while (e != 0){p = (LNode*)malloc(sizeof(LNode));p->data = e;p->next = L->next;L->next = p;printf("请输入节点元素值:");scanf_s("%d", &e);}return L;}void DestroyList(LinkList &L){LNode *p;while (L){p = L->next;free(L);L = p;}}//重置单链表L,释放除头结点以外的内存空间void ClearList(LinkList L)//不改变L{LNode *p, *q;p = L->next;while(p){q = p->next;free(p);p = q;}L->next = NULL;//头指针的指针域变为空}Status ListEmpty(LinkList L){if (L->next)return TRUE;elsereturn FALSE;}int ListLength(LinkList L){int i = 0;LNode *p;p = L->next;while (p){i++;p = p->next;}return i;}ElemType GetElem(LinkList L, int i){int j = 1;//计数器LNode *p;ElemType e;p = L->next;//p指向第一个节点while (p&&j < i){p = p->next;j++;}e = p->data;printf("%d\n", e);return e;}int LocateElem(LinkList L,ElemType &e){int i = 1;LNode *p;p = L->next;while (p->data != e){p = p->next;i++;}printf("%d\n", i);return i;}Status PriorElem(LinkList L, ElemType cur_e, ElemType &pre_e){LNode *p, *q;p = L->next;//p指向第一个节点while (!p){q = p->next;if (q->data == cur_e){pre_e = p->data;return OK;}p = q;//p向后移}return OK;}Status NextElem(LinkList L, ElemType cur_e, ElemType &next_e){LNode *p;p = L->next;while (!p){if (p->data == cur_e){next_e = p->next->data;return OK;}p = p->next;}return OK;}Status ListInsert(LinkList &L,ElemType &e){LNode *p, *q;p = L->next;while (p->data > e)p = p->next;q = (LNode *)malloc(sizeof(LNode));q->data = e;q->next = p->next;p->next = q;return OK;}Status ListDelete(LinkList &L, ElemType &e){LNode *p, *q;p = L->next;if (p->data == e){L->next = p->next;free(p);}else{while (p->data != e){q = p;p = p->next;}q->next = p->next;free(p);}return OK;}void Reverse(LinkList &L){LNode *p, *q;p = L->next;L->next = NULL;while (p){q = p->next;p->next = L->next;L->next = p;p = q;}free(q);}void PrintList(LinkList L){LNode *p;p = L->next;while (p){printf("%d", p->data);p = p->next;}printf("\n");}

#include "SqList.h"int main(){LinkList L;ElemType e;int i;CreateList(L);    PrintList(L);printf("插入的元素为:");scanf_s("%d", &e);ListInsert(L, e);PrintList(L);printf("删除的元素为:");scanf_s("%d", &e);ListDelete(L, e);PrintList(L);printf("您所查找的元素的位置为:\n");scanf_s("%d", &i);LocateElem(L, i);printf("您定位的元素值为:\n");scanf_s("%d", &e);GetElem(L, e);printf("就地逆置单链表L:");Reverse(L);PrintList(L);return 0;}

1 0