双链表一系列操作
2015-08-04 12:30
274 查看
#include<stdio.h> #include<malloc.h> typedef int bool; #define false 0//后面没分号; #define true 1 typedef char Elemtype; typedef struct Snode { Elemtype data; struct Snode *prior; struct Snode *next; }snode; void initlinklist(snode **p); void destorylist(snode **p); bool listinsert(snode *p,int i,Elemtype e); void displist(snode *p); int lengthlist(snode *h); bool listempty(snode *p); bool getlistdata(snode *p,int i,Elemtype *e); int locate(snode *p,Elemtype e); bool deletelist(snode *p,int i); void initlinklist(snode **p) { if((*p) == NULL) { *p = malloc(sizeof(snode)); (*p)->prior = NULL; (*p)->next = NULL; } } void destorylist(snode **p) { snode *q = *p; snode *s; while(q) { s = q->next; free(q); q = s; } *p = NULL; } bool listinsert(snode *p,int i,Elemtype e) { snode *s;//定义放在最前面。 int j = 0;//当J=0是p指向头结点。保持好对应关系,让他们同增。 snode *q=p;//q负责找到第i-1个结点; s = malloc(sizeof(snode)); s->data = e; while(j<i-1&&q) { q = q->next; j++; } if(q) { s->next = q->next; if(q->next)//如果插入最后一个节点,则不赋值; q->next->prior = s; s->prior = q; q->next = s; return true; } else return false; } void displist(snode *p) { snode *s = p->next; while(s) { printf("%c\n",s->data); s = s->next; } } int lengthlist(snode *h) { int len = 0; snode *s = h; while(s->next)//这里(s->next)稍加注意 { len++; s = s->next; } return len; } bool listempty(snode *p) { return p->next == NULL; } bool getlistdata(snode *p,int i,Elemtype *e) { int j=0; snode *s = p; while(j<i&&s) { s = s->next; j++; } if(s == NULL) return false; else { *e = s->data; return true; } } bool deletelist(snode *p,int i) { int j=0; snode *s=p; snode *res; while(j<i-1&&s) { s = s->next; j++; } if(s == NULL) return false; else { res = s->next; if(res == NULL) return false; if(res->next) res->next->prior = s; s->next = res->next; free(res); return true; } } int locate(snode *p,Elemtype e) { int i = 1; snode *s = p->next; while(s->data!=e&&s) { i++; s=s->next; } return i; } int main(void) { snode *p = NULL; Elemtype e; initlinklist(&p); listinsert(p,1,'a'); listinsert(p,2,'b'); listinsert(p,3,'c'); listinsert(p,4,'d'); listinsert(p,5,'e'); printf("输出双链表元素如下\n"); displist(p); printf("输出双链表的长度%d\n",lengthlist(p)); listempty(p); listinsert(p,4,'f'); printf("输出双链表元素如下\n"); displist(p); getlistdata(p,3,&e); printf("第3个字母为%c\n",e); printf("输入你要搜寻的字母\n"); scanf("%c",&e); printf("%c在第%d个位置\n",e,locate(p,e)); if(deletelist(p,5)) displist(p); else printf("dsfsf"); destorylist(&p); return 0; }
相关文章推荐
- hadoop安全模式
- Oracle 多字段的in
- HDOJ 1016 Prime Ring Problem(dfs)
- java使用cookies
- Python中return语句用法实例分析
- SER-U ftp服务器的配置
- redis学习笔记(二)
- django学习笔记之(model设计与实现)
- Android(java)学习笔记139:在TextView组件中利用Html插入文字或图片
- UART中的硬件流控RTS与CTS
- pickle和cPickle——python对象序列化
- 玲珑杯Uinty开发心得——安卓平台发布
- Android Parcelable和Serializable的区别(三)
- CSS 的黑科技
- Recurrent network model for kinematic tracking
- Volley实战用法
- LeetCode 191_Number of 1 Bits
- 手持平台纹理格式说明
- makefile 中 $@ $^ %< 使用
- C++new和delete重载