单向加头链表的构建插入删除查找输出
Posted lzjlzj
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了单向加头链表的构建插入删除查找输出相关的知识,希望对你有一定的参考价值。
#include <stdio.h> #include <malloc.h> typedef struct lianbiao *ptr; struct lianbiao { int data; ptr next; }; int main(void) { ptr create(); void out(ptr p); ptr search(ptr p, int x); ptr del(ptr h, int x); ptr add(ptr head, int x); int delEl, searchEl, addEl, delResult, searchResult; ptr l = create(); //构建初始链表 printf("初始链表为:"); //输出初始链表 out(l); printf(" "); //查找元素 printf("输入待查找元素:"); scanf("%d", &searchEl); searchResult = search(l, searchEl); if (searchResult) { searchResult = search(l, searchEl)->data; printf("元素%d查找成功 ", searchResult); } else printf("待查找元素不存在! "); printf(" "); //删除元素 printf("输入待删除元素:"); scanf("%d", &delEl); delResult = del(l, delEl); if (delResult) printf("删除成功! "); else printf("待删除元素不存在! "); printf(" "); //插入元素 printf("输入待插入元素:"); scanf("%d", &addEl); add(l, addEl); } ptr create() // 构建链表 { ptr p, head, last; int x; //创建头结点 head = (ptr)malloc(sizeof(ptr)); head->data = 0; last = head; last->next = NULL; //添加链表元素 printf("构建初始链表(输入0以结束):"); scanf("%d", &x); while (x != 0) { p = (ptr)malloc(sizeof(ptr)); p->data = x; //把新元素插入链表 if (x > last->data) //待插入元素大于所有节点 { last->next = p; p->next = NULL; last = p; } else if (x < head->next->data) //待插入元素小于所有节点 { p->next = head->next; head->next = p; } else //一般情况 { ptr f = head, s = f->next; while (x > s->data) { f = s; s = s->next; } p->next = s; f->next = p; } scanf("%d", &x); } return head; } void out(ptr p) //输出链表 { p = p->next; while (p != NULL) { printf("%5d", p->data); p = p->next; } printf(" "); }; ptr search(ptr p, int x) //搜索元素 { while (p != NULL) { if (p->data == x) return p; p = p->next; } return 0; } ptr del(ptr h, int x) //删除元素 { ptr f, s; f = h; s = h->next; while (s->data != x) { f = s; s = s->next; if (s->next == NULL) break; } if (s->data == x) { f->next = s->next; free(s); return 1; } else return 0; } ptr add(ptr head, int x) { ptr p, last, yyy; yyy = head; while (yyy->next != NULL) yyy = yyy->next; last = yyy; last->next = NULL; p = (ptr)malloc(sizeof(ptr)); p->data = x; //把新元素插入链表 if (x > last->data) //待插入元素大于所有节点 { last->next = p; p->next = NULL; last = p; } else if (x < head->next->data) //待插入元素小于所有节点 { p->next = head->next; head->next = p; } else //一般情况 { ptr f = head, s = f->next; while (x > s->data) { f = s; s = s->next; } p->next = s; f->next = p; } printf("添加完成! 现在的链表为:"); out(head); printf(" "); }
以上是关于单向加头链表的构建插入删除查找输出的主要内容,如果未能解决你的问题,请参考以下文章