C/C++之单链表的节点删除和插入

#include<stdio.h>
#include<stdlib.h>

//Linked-list structure
typedef struct ListNode
{
  int data;                      //data field
  struct ListNode *next;         //point to next node
} Node,*PNode;

//creat a linklist,the counts of node is cnt,datasource is pData
PNode CreatLinkedList(const int cnt,int *pData)
{
  //malloc head node
  PNode pHead=(PNode)malloc(sizeof Node);
  if(pHead==NULL)//if phead is null
  {
    return NULL;
  }
  int i=0;
  PNode pRail=pHead;            //rail node for traversing linked list
  while(i<cnt)
  {
    PNode pNext=(PNode)malloc(sizeof Node);//malloc every node
    if(pNext==NULL)
      break;
    pNext->data=*pData++;

    pRail->next=pNext;
    pNext->next=NULL;
    pRail=pNext;

    ++i;
  }

  return pHead;
}

//delete the node that the data==num 
PNode DeleteNode(PNode list,int num)
{
  if(list->data==num)
  {
    return list->next;
  }

  PNode p=list;
  PNode pn=NULL;

  while (p!=NULL)
  {
    pn=p;                         //save privious node
    p=p->next;                     //increase
    if (p==NULL)
    {
      printf("There is no finding in the list!\n");
    }
    else if(p->data==num)
    {
      pn->next=p->next;
    }
    else
    {
      //printf("There is no finding in the list!\n");
    }
  }
  return list;
}

//insert one node(data=ins_num) behind the node which data==num
PNode InsertNode(PNode list,int num,int ins_num)
{
  PNode p=list;

  while (p!=NULL)
  {
    if(p->data==num)
    {
      PNode pNew=(PNode)malloc(sizeof PNode);
      pNew->data=ins_num;
      pNew->next=p->next;
      p->next=pNew;
      break;
    }
    //increase
    p=p->next;
  }

  return list;
}

//main.c   test
int main()
{
  int n=5;
  int a[5]={0,1,2,3,4};
  PNode lnode;
  lnode=CreatLinkedList(n,a);
  DeleteNode(lnode,5);
  PNode p=InsertNode(lnode,3,6);

  //printf the linked list
  while(p->next!=NULL)
  {
    p=p->next;
    printf("%d\n",p->data);
  }
  printf("Hello World\n");
  system("pause");
  return 0;
}




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值