链表的基本操作
2014-08-27 15:54
190 查看
#include <stdio.h> #include <malloc.h> typedef struct list{ int value; struct list *next; }node; node* add(node *head) //增加节点 { node *p = head, *p2; int tmp; char ch; scanf("%d", &tmp); ch = getchar(); p2 = (node *)malloc(sizeof(node)); p2->value = tmp; p2->next = NULL; if (NULL == p) return p2; while (p->next != NULL) p = p->next; p->next = p2; return head; } node* del(node *head) //删除节点 { int tmp, flag; char ch; node *p = head, *pre = NULL; if (NULL == p) { printf("ERROR! List is NULL!\n"); return head; } scanf("%d", &tmp); ch = getchar(); flag = 0; while (p) { if (p->value == tmp) { flag = 1; break; } pre = p; p = p->next; } if (0 == flag) { printf("ERROR! There is no %d.\n", tmp); return head; } if(NULL == pre) { p = p->next; free(head); return p; } pre->next = p->next; free(p); return head; } void print(node *head) //遍历链表 { node *p = head; while (p) { printf("%d\t", p->value); p = p->next; } printf("\n"); return; } node *rev(node *head) //翻转链表 { node *p = head, *pre = NULL, *tmp; while (p) { tmp = p; p = p->next; tmp->next = pre; pre = tmp; } return pre; } int main() { char c, ch; node *head = NULL; printf("a:增加节点;\td:删除节点;\tp:遍历链表;\tr:翻转链表.\n"); while (scanf("%c", &c) != EOF) { ch = getchar(); switch (c) { case 'a': head = add(head); break; case 'd': head = del(head); break; case 'p': print(head); break; case 'r': head = rev(head); break; default: printf("Invalid input!\n"); } printf("a:增加节点;\td:删除节点;\tp:遍历链表;\tr:翻转链表.\n"); } return 0; }
相关文章推荐
- 算法(05):基本链表的操作及双向链表
- 链表的基本操作
- 双链表基本操作
- 带头结点的单链表的12个基本操作
- C++链表基本操作
- 链表的基本操作
- 单链表的基本操作
- bo2-8.cpp 不带头结点的单链表(存储结构由c2-2.h定义)的部分基本操作(9个)
- bo2-4.cpp设立尾指针的单循环链表(存储结构由c2-2.h定义)的12个基本操作
- 单链表和双链表上的基本操作
- 数据结构类型定义及基本操作汇总(一)--线性表,单链表,栈和队列
- 用C语言编写一个包含链表的初始化、插入、删除、查找等基本操作的程序。
- 链表队列与二叉树基本操作
- bo2-9.cpp 不带头结点的单链表(存储结构由c2-2.h定义)的部分基本操作(2个)
- 链表的基本操作
- 单链表的基本操作
- 双向循环链表的基本操作
- 单链表基本操作c语实现
- 链表的一些基本操作
- 链表的基本操作