数据结构学习笔记之Linklist

Data Structrue

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所指示的位置之后

整个过程如图所示:
Linklist

核心代码:

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

过程如图所示:
Linklist

核心代码:

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);
   }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值