单链表的各种操作

//  重要的是find 操作
//define the information about the data;
typedef struct {
  char num[5];
  char name[30];
  char sex[3];
  char phone[13];
  char addr[31];
} DataType;


//define a node;
typedef struct node {
  DataType data;
  struct node * next;
} ListNode,*pListNode;

ListNode* CreateList (void)     //初始化单链表
{
  ListNode * head = (ListNode * )malloc(sizeof(ListNode));


  if(head == NULL) {
    printf("in the CreateList: can't malloc the memory");
    exit(0);
  }
  head->next = NULL;
  return head;
}

// 另外两种初始化单链表的方式      传递二级指针是为了改变一级指针指向的内容
//  就是为了ListNode* 指针指向一个节点单元   为头结点
void CreateList1( ListNode* *head){   
(*head) = ( ListNode* )malloc( sizeof(ListNode));
if( (*head) == NULL )
{
printf("in the CreateList: can't malloc the memory");
         exit(0);
}

(*head)->next=NULL;
}

void CreateList2( pListNode *head ){
*head = ( ListNode* )malloc( sizeof(ListNode) );
if( head == NULL  )
{
printf("can't malloc the memory");
exit(0);
} 
(*head)->next = NULL;
}

//  找到链表中NUm所在的结点, 返回指向NUM指点的指针cur,和pre指针为cur指针的前一个指针
ListNode *find_num(ListNode *head, char num[], ListNode* &pre){ //pre 是ListNode*指针的一个引用,其实不用引用 传递二级指针也可以,改变指针的内容嘛
ListNode *cur;
        pre=null;
cur=head->next;
while( strcmp(cur->data.num,num) )
{
pre=cur;
cur=cur->next;
}
return cur;
} 
// 头插法 每次在第一个位置插入结点
int InsertList( ListNode *head ){
ListNode *p;
p=( ListNode *)malloc(sizeof(ListNode));
if( p==NULL )
{
printf("can't malloc\n");
//exit(-1);
return 0;
}
p->data=Input_Data();// 这个是插入结点内容的函数
p->next=NULL;
p->next=head->next;
head->next=p;
return 1;
}


void displayList( ListNode *head ){

ListNode *p=head->next;
while( p )
{
Output_Data(p->data);;
p=p->next;
printf("\n");
}


}

// 删除链表里有num的结点
int deleteList( ListNode *head, char num[] ){
ListNode *cur,*pre=NULL;
cur=find_num(head,num,pre);// 这是上面find函数 返回前一个结点的指针 和 当前指针
    if( cur == NULL )
    {
       printf("cant find:%s\n",num);
       return 0;
    }
    else if( pre == NULL )
     head->next = cur->next;
    else
      pre->next = cur->next;
    return 1;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值