链表(C语言)
2015-08-06 10:19
316 查看
#include <stdio.h> #include <stdlib.h> #define number 5 typedef int elemType; typedef struct List { elemType elem; struct List *next; }Node; //创建单链表 struct List *createList(int num) { Node *head,*p1,*p2; if((head=(Node*)malloc(sizeof(Node)))==NULL) { printf("create error\r\n"); exit(0); } head->elem=0; head->next=NULL; p1=head; int i; for(i=0;i<num;i++) { if((p2=(Node*)malloc(sizeof(Node)))==NULL) { printf("create error\r\n"); exit(0); } p2->elem=i; p2->next=NULL; p1->next=p2; p1=p2; } return head; } //遍历单链表 void displayList(Node *head) { Node *p1; if(head==NULL) { printf("空链表\r\n"); //exit(0); } else { for(p1=head->next;p1!=NULL;p1=p1->next) { printf("%d\t",p1->elem); } printf("\r\n"); } } //插入节点 pos从1开始 void insertList(Node* head,elemType elem,int pos) { Node *p1,*p2; int i=1; p1=head; while(p1->next!=NULL) { if(i>=pos)//pos=1 break; p1=p1->next; i++; } if((p2=(Node*)malloc(sizeof(Node)))==NULL) { printf("insert create rear error"); exit(0); } if(p1->next!=NULL)//表中插入 { p2->elem=elem; p2->next=p1->next; p1->next=p2; } else//在链表尾插入 { p2->elem=elem; p2->next=NULL; p1->next=p2; } } //删除结点 pos从1开始 返回结点的值 elemType moveList(Node* head,int pos) { elemType temp; Node *p1,*p2; int i=1; p1=head; while(p1->next!=NULL) { if(i>=pos) { break; } i++; p1=p1->next; } p2=p1->next; if(p2->next==NULL) p1->next=NULL; else p1->next=p2->next; return p2->elem; } //查找元素 返回元素位置 找不到返回-1 int searchList(Node* head,elemType elem) { Node* p1; p1=head; int i=1; while(p1->next!=NULL) { if(p1->next->elem==elem) { return i; } i++; p1=p1->next; } printf("找不到该元素\r\n"); return -1; } //判断链表是否为空 bool isEmptyList(Node* head) { return head==NULL;//||head->next==NULL; } //清除链表的所有节点,包含头节点 struct List* clearList(Node* head) { Node *p1,*p2; p1=head; //int i=1; while(p1!=NULL) { p2=p1->next; free(p1); p1=NULL; p1=p2; //printf("%d\t",i++); } head=NULL;//将所指的链表指针设为NULL return head; } int main() { Node *head; elemType temp; head=createList(number); displayList(head); insertList(head,8,3); displayList(head); insertList(head,9,7); displayList(head); temp=moveList(head,3); displayList(head); printf("移除:%d\r\n",temp); temp=moveList(head,6); displayList(head); printf("移除:%d\r\n",temp); temp=searchList(head,3); if(temp!=-1) printf("位置:%d\r\n",temp); temp=searchList(head,7); if(temp!=-1) printf("位置:%d\r\n",temp); if(!isEmptyList(head)) printf("not empty\r\n"); head=clearList(head); displayList(head); if(isEmptyList(head)) printf("empty\r\n"); return 0; }
相关文章推荐
- [C/C++]反转链表
- 动易2006序列号破解算法公布
- C#实现基于链表的内存记事本实例
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua和C语言的交互详解
- Lua教程(七):数据结构详解
- 解析从源码分析常见的基于Array的数据结构动态扩容机制的详解
- 超大数据量存储常用数据库分表分库算法总结
- C#数据结构与算法揭秘二
- C#冒泡法排序算法实例分析
- C#数据结构揭秘一
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C#实现的算24点游戏算法实例分析
- 关于C语言中参数的传值问题
- 深入C++中API的问题详解
- 基于C语言string函数的详解
- C语言内存对齐实例详解
- c语言实现的带通配符匹配算法