c语言单链表的各种操作<未完>
2013-01-04 16:06
417 查看
#include<stdio.h> #include<stdbool.h> struct Node { int val; Node* next; }; Node* Create() { bool bFlag=true; Node *pHead=NULL; Node *pCur=NULL; Node* pTemp=NULL; int nVal; pHead=(Node*)malloc(sizeof(Node)); if(NULL==pHead) { return NULL; } pHead->next=NULL; pCur=head; while(bFlag) { pTemp=(Node*)malloc(sizeof(Node)); printf("please input node value,if the value is 0 input finished."); scanf("%d",&nVal); if(nVal!=0) { pTemp->val=nVal; pTemp->next=NULL; pCur->next=pTemp; pCur=pTemp; } else { bFlag=false; } } pHead=pHead->next; pCur->next=NULL; return pHead; } int length(Node* head) { if(head==NULL) { return 0; } int i=0; Node* cur=head; while(cur!=NULL) { i++; cur=cur->next; } return i; } bool print(Node *head) { if(NULL==head) { return false; } printf("list info:"); Node *cur=head; while(NULL!=cur) { printf("%d\n",cur->val); cur=cur->next; } return true; } Node* del(Node* head, int pos) { if((head==NULL)||(pos<1)||(pos>length(head))) { return NULL; } Node* cur=head; if(pos==1) { cur=cur->next; free(head); head=NULL; return cur; } //定位到删除节点的前一个节点 int i=0; for(i=0;i<pos-1;i++) { cur=cur->next; } cur->next=cur->next->next; return head; } Node* addafterpos(Node *head, int pos, int val) { if((head==NULL)||(pos<1)||(pos>length(head))) { return NULL; } Node* newnode=(Node*)malloc(sizeof(Node)); if(newnode==NULL) { return NULL; } newnode->val=val; newnode->next=NULL; Node* cur=head; if (pos==length(head)) { while(cur->next!=NULL) { cur=cur->next; } cur->next=newnode; } int i=0; for(i=0;i<pos;i++) { cur=cur->next; } newnode=cur->next; cur->next=newnode; return head; } Node* insertbefore(Node* head, int pos, int val) { if((head==NULL)||(pos<1)||(pos>length(head))) { return NULL; } Node* newnode=(Node*)malloc(sizeof(Node)); if(newnode==NULL) { return NULL; } newnode->val=val; newnode->next=NULL; Node* cur=head; if(pos==1) { newnode->next=cur; return newnode; } int i=0; for(i=0;i<pos-1;i++) { cur=cur->next; } newnode->next=cur->next; cur->next=newnode; return head; } int main() { Node *head; int len; head=Create(); len=length(head); printf("len:%d", len); print(head); head=del(head,1); print(head); head=addafterpos(head,4,5); print(head); head=insertbefore(head,1,1); print(head); return 0; }
相关文章推荐
- &lt;org manual&gt;翻译--4.4 链接的各种操作
- c语言:常用各种头文件的作用,如:#include &lt;stdlib.h&gt;
- <C语言>结构体的各种定义、初始化、操作代码实例----注释详解
- <iOS>关于子线程和block中操作主线程界面的控件讨论
- WEBGL 2D游戏引擎研发系列 第五章 <操作显示对象>
- <数据结构>单链表的C语言实现
- <Head First Java>学习笔记--第四章:方法操作实例变量 对象的行为
- C语言学习代码<一>
- android中对/data/data/<package name>/files下文件的读写操作
- C语言指针教程----入门到精通<一>
- 用C语言实现单链表的各种操作
- 关于C语言中的按位与(&)按位或(|)按位异或(^)取反(~)左移(<<)右移(>>)
- <Programming_in_Lua> 笔记(未完)
- c语言深入理解<2>
- LDAP学习笔记<四>jldap实现Java对LDAP的基本操作
- C语言第四天课堂笔记<详细+注释>
- 第13周 项目5-字符串操作(1)-<统计A的个数>
- iOS开发中对OC字符串的相关操作<转>
- C++中各种类型转换的具体细节<未完成>
- c文件操作<1>