线性表的链式存储

来源:互联网 发布:房地产数据 知乎 编辑:程序博客网 时间:2024/05/16 08:31
#include <stdio.h>#include <malloc.h>#include <stdlib.h>#define OK 0#define ERROR -1#define TRUE 1#define FALSE 0#define ElemType inttypedef struct Node{ElemType data;struct Node *next;}Node;//创建一个空链表,返回链表头结点Node* createLinkList();//向头结点为head的链表的pos位置插入元素e,pos从1开始int insertList(Node *head, int pos, ElemType e);//删除链表中pos位置的元素,并返回其值int removeList(Node *head, int pos, ElemType *e);//得到pos位置的元素int getElem(Node head, int pos, ElemType *e);//查找元素e,找到返回TRUE,否则返回FALSEint findElem(Node head, ElemType e);//遍历头结点为head的链表int traverse(Node head);int main(){Node *head = createLinkList();for (int i=1; i<=1000; i++)insertList(head, i, i);ElemType e;//removeList(head, 500, &e);getElem(*head, 1000, &e);printf("findElem:%d\n", e);traverse(*head);int result = findElem(*head, 500);printf("result:%d\n", result);system("pause");return 0;}Node* createLinkList(){//为头结点分配存储空间Node *head = (Node *)malloc(sizeof(Node));if (!head){printf("内存分配失败,程序将退出\n");exit(-1);}//创建空链表,所以头结点的下一个结点为NULLhead->next = NULL;return head;}int insertList(Node *head, int pos, ElemType e){if (!head){printf("插入失败,链表不存在\n");return ERROR;}//首先定义一个临时结点指向链表头结点,和一个计数器iNode *p = head;int i = 1;//找到要插入位置的前一个结点while (p && i < pos){p = p->next;i++;}if (!p || i > pos){printf("插入失败,插入位置有误\n");return ERROR;}//为新插入的结点分配存储空间Node *newNode = (Node *)malloc(sizeof(Node));if (!newNode){printf("插入失败,分配存储空间失败,程序将退出\n");exit(-1);}//把新插入结点的下一个结点改为之前结点的下一个结点newNode->next = p->next;//把上一个结点的下一个结点改为新插入的结点p->next = newNode;newNode->data = e;return OK;}int removeList(Node *head, int pos, ElemType *e){if (!head){printf("删除失败,链表不存在\n");return ERROR;}Node *p = head;int i = 1;//找到待删结点的前一个结点while (p && i < pos){p = p->next;i++;}if (!p || i > pos){printf("删除失败,删除位置有误\n");return ERROR;}//先暂存待删除结点Node *q = p->next;//使待删除结点的前一个结点的指针域指向待删除结点的下一个结点p->next = p->next->next;//取出删除的值然后释放待删除结点的存储空间*e = q->data;free(q);return OK;}int getElem(Node head, int pos, ElemType *e){if (!&head){printf("查找失败,链表不存在\n");return ERROR;}//从第一结点,也就是头结点的下一个结点开始查找Node *p = head.next;int i = 1;while (p && i < pos){p = p->next;i++;}if (!p || i > pos){printf("查找失败,查找位置有误\n");return ERROR;}*e = p->data;return OK;}int findElem(Node head, ElemType e){if (!&head){printf("查找失败,链表不存在\n");return ERROR;}Node *p = head.next;while (p){if (p->data == e){return TRUE;}p = p->next;}return FALSE;}int traverse(Node head){if (!&head){printf("要遍历的链表不存在\n");return ERROR;}Node *p = head.next;while (p){printf("%d ", p->data);p = p->next;}printf("\n");return OK;}

0 0