数据结构学习笔记之Linklist
2015-06-11 00:11
423 查看
Data Structrue
1. LinkList
LinkList
Linklist形式如图
Linklist 定义:
typedef struct Node * PtrToNode;// typedef PtrToNode List;//表示链表,指向链表的头节点 typedef PtrToNode Position; struct Node{ ElementType Element; Position Next; };
Node有两个域,一个是data field(element),用于表示数据。第二个数据域是,ptr field(Ptr),用于指向下一个节点。
下面是一些关于链表操作的函数
判空
/*return true if L is empty*/ int IsEmpty(List L){ return L->next=NULL; }
判断某个位置是否为最后一个节点
/*return true if p is the last position in L*/ int IsLast(Postiion p,List L){ return p->next=NULL; }
查找指定元素x在L中的位置
/*return position of x in L,NULL if not found*/ /*p=NULL or p->next=NULL depends on p=L->next or p=*/ Position Find(ElementType x,List L){ Position p; p=L->next; while(p!=NULL&&p->data!=x){ p=p->next; } return p; }
将一个元素x插入到由p所指示的位置之后
整个过程如图所示:
核心代码:
tmp->Element=x; tmp->Position=p->Position; p->next=tmp;
代码:
void Insert(Position p,ElementType x,List L){ Position tmp; tmp=(Position)malloc(sizeof(Position)); if(tmp==NULL){ printf("malloc error"); } tmp->Element=x; tmp->next=p->next; p->next=tmp; }
创建链表L
核心代码如上图所示。只是不断的在头指针即L所指示位置之后插入。
Position Create_List() { Position head = NULL; head = (Position)malloc(sizeof(Position)); if (NULL == head) { printf("memory out of use/n"); return NULL; } head->next = NULL; head->data = 0; return head; } //尾插法建立链表 int insert_form_tail(Position head, int num) { Position temp = head; Position new_node = NULL; new_node = (Position)malloc(sizeof(Position)); if (NULL == new_node) { printf("memory out of use/n"); return -1; } S while (temp->next != NULL) { temp = temp->next; } //将新结点插入到链表的最后 new_node->data = num; new_node->next = NULL; temp->next = new_node; return 0; }
删除L中的某个元素x
过程如图所示:
核心代码:
tmp=p->next; p->next=tmp->next;
代码:
/*find the previous position before x in L ,if not found return next field of returned*/
Position FindPrevious(ElementType x,List L){
Position p;
p=L;
while(p->next!=NULL&&p->next->Element!=x)
p=p->next;
return p;
}
void Delete(ElementType x,List L){
Position p,tmp;
p=FindPrevious(x,L);
Position FindPrevious(ElementType x,List L){
Position p;
p=L;
while(p->next!=NULL&&p->next->Element!=x)
p=p->next;
return p;
}
if(!IsLast(p,L)){
tmp=p->next; p->next=tmp->next;
free(tmp);
}
}
相关文章推荐
- 数据结构基础(1)--数组C语言实现--动态内存分配
- 数据结构和算法-007 队列
- 大话数据结构—散列表查找(哈希表)
- 数据结构表达式求值
- SDUT 2137 数据结构实验之求二叉树后序遍历和层次遍历
- BZOJ 4085:[Sdoi2015]quality(round 2 音质检测)(数据结构)
- MySQL索引背后的数据结构及算法原理
- 数据结构实验图论一:基于邻接矩阵的广度优先搜索遍历
- leetcode--Binary Tree Inorder Traversal
- Codeforces Round #306 (Div. 2) D.E. 解题报告
- Json数据结构
- XML、JSON数据结构解析
- 大话数据结构—多路查找树(B树)
- RDP协议详解
- 数据结构(二)---栈:
- JAVA数据结构之String、StringBuffer和StringBuilder之间的区别
- 数据结构
- 数据结构——算法之(043)(c++各种排序算法实现)
- 数据结构——算法之(042)(字符串移位包含的问题, s1是否可以由s2移位后得到)
- 数据结构——算法之(041)(寻找数组中的最大值和最小值)