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);
}
}