数据结构---线性表链式实现
2015-01-08 10:15
148 查看
主要参考的严老师那本教材上的:
写的比较快,可能代码的可读性不是很好。
写的比较快,可能代码的可读性不是很好。
//带头结点的单链表 #include <stdio.h> #include <malloc.h> #define ElemType int typedef struct node { ElemType data; struct node *next; }node; //用data来初始化并分配内存,返回一个新节点 node *newNode(ElemType data) { node *pNode=(node *)malloc(sizeof(node)); if(!pNode) return NULL;//失败 pNode->data=data; pNode->next=NULL; return pNode; } //创建n个元素的链表(主要是分配空间),并且输入来初始化 node* createList(int n) { node *head=(node *)malloc(sizeof(node)); if(!head) return NULL;//失败 head->next=NULL; node *cur=head; for (int i=0; i<n; i++) { ElemType tmp; scanf("%d",&tmp); node *tmpNode=newNode(tmp); if(!tmpNode) return NULL;//失败 cur->next=tmpNode; cur=cur->next; } return head; } //输出链表所有元素 void printList(node *head) { node *cur=head; while(cur->next!=NULL) { printf("%d ",cur->next->data); cur=cur->next; } printf("\n"); } //按照位置查找pos(除去头结点外,第一个元素算作位置0,从0开始)处元素,取得数据域 int searchByPos(node *head,int pos,ElemType *e) { node *cur=head; for (int i=0; i<pos && cur->next!=NULL; i++) cur=cur->next; if(cur->next!=NULL) { *e=cur->next->data; return 1; } else return 0; } //在位置pos(前)插入一个新元素,pos:除去头结点外,有效节点的pos从0开始 //pos合法范围:0--len-1;不过程序中有检测 int insertByPos(node *head,int pos,ElemType e) { node *cur=head; node *tmpNode=newNode(e); int i; if(!tmpNode) return 0;//插入失败 for (i=0; i<pos && cur->next!=NULL; i++) cur=cur->next; if(cur->next==NULL&&i>=pos)//可以直接在尾部追加的情况 { cur->next=tmpNode; return 1; } else if(i>=pos) { tmpNode->next=cur->next; cur->next=tmpNode; return 1; } else return 0;//pos位置不存在造成的无法插入 } //删除某个位置的元素,用*e保存它的值 int deleteByPos(node *head,int pos,ElemType *e) { node *cur=head; int i; for (i=0; i<pos && cur->next!=NULL; i++) cur=cur->next; if(cur->next==NULL) return 0;//不存在这个位置,删除失败 else { node *tmp=cur->next; cur->next=cur->next->next; free(tmp); return 1; } } int main() { node *head=createList(5); printList(head); insertByPos(head,3,55); printList(head); ElemType tmp; deleteByPos(head,5,&tmp); printList(head); return 0; }
相关文章推荐
- 基础数据结构--线性表链式实现
- 数据结构第二章之线性表C实现
- 数据结构:线性表(顺序存储)顺序表类(实现顺序表的创建,输出,插入,删除功能)
- 重温数据结构-线性表的顺序表示与实现
- javascript实现数据结构:线性表--简单示例及线性表的顺序表示和实现
- 数据结构3:线性表的静态链表的表示和实现
- 线性表数据结构C语言实现
- 数据结构--线性表(顺序实现,链式实现,多项式计算)
- 数据结构:线性表的链式存储(单向链表)--Java实现
- 数据结构:线性表的顺序存储--Java实现
- 数据结构-----线性表的顺序表示与实现
- 数据结构:线性表(顺序存储)顺序栈类(实现创建,输出,入栈出栈,读栈顶元素功能)
- 数据结构C语言之线性表简单实现
- 严蔚敏版《数据结构》第二章线性表的算法C语言实现
- 数据结构:线性表的链式存储(双向链表)--Java实现
- 线性表链式实现
- 算法与数据结构--实现线性表的合并操作(合并后按非递减排列)--算法2.6
- (C语言)栈的线性结构实现(数据结构八)
- 线性表链式 实现
- 数据结构------线性表的链式表示与实现