链表及操作

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

typedef struct Node
{
 int date;
 struct Node * pNext;
}NODE, *PNODE;

PNODE create_list(void);
void traversal(PNODE);
bool is_empty(PNODE);
int len_list(PNODE);
void sort_list(PNODE);
bool insert_list(PNODE pHead,int pos, int val);
bool delete_list(PNODE pHead,int pos, int * val);


int main()
{

 int val;
 PNODE pHead;
 pHead = create_list ();
 traversal(pHead);
 int len = len_list(pHead);
 printf("链表的长度为%d\n",len);
 delete_list (pHead, 2, &val);
 //insert_list (pHead,3,100);
 //sort_list(pHead);
 traversal(pHead);
 getchar();
 getchar();
 return 0;
}

PNODE create_list(void)
{
 int len;
 int val;

 PNODE pHead = (PNODE)malloc(sizeof(NODE));
 if(NULL == pHead)
 {
  printf("分配失败!");
  exit(-1);
 }
 PNODE pTail = pHead;
 pTail->pNext = NULL;

 printf("请输入链表的元素个数:");
 scanf("%d", &len);

 for (int i=0; i<len; i++)
 {

  printf("请输入第%d个元素的值: ",i+1);
  scanf("%d", &val);
  PNODE pNew = (PNODE)malloc(sizeof(NODE));
  if(NULL == pNew)
     {
    printf("分配失败!");
    exit(-1);
     }
  pNew->date = val;
  pTail->pNext = pNew;
  pNew->pNext = NULL;
  pTail = pNew;
 }
 return pHead;
}

void traversal(PNODE pHead)
{
 PNODE p = pHead->pNext;
 while (p != NULL)
 {
  printf("%d ",p->date);
  p = p->pNext ;
 }
 printf("\n");
 return;
}

bool is_empty(PNODE pHead)
{
 if(NULL == pHead->pNext)
  return true;
 else
  return false;
}

int len_list(PNODE pHead)
{
 int len = 0;
 PNODE p = pHead->pNext;
 while(NULL != p)
 {
  ++len;
  p = p->pNext;
 }
 return len;
}

void sort_list(PNODE pHead)
{
    int i,j;
 PNODE p,q;
 int t;
 int len = len_list (pHead);
 for(i=0,p=pHead->pNext; i<len-1; i++,p=p->pNext)
  for(j=i+1,q=p->pNext; j<len; j++,q=q->pNext)
  {
   if(p->date > q->date )
   {
      t = p->date;
      p->date = q->date ;
      q->date = t;
   }
  }
}

bool insert_list(PNODE pHead,int pos, int val)
{
 int i = 0;
 PNODE p = pHead;
 while(NULL != p && i<pos-1)
 {
  p = p->pNext;
  ++i;
 }

 if(NULL == p && i>pos-1)
  return false;
    PNODE pNew = (PNODE)malloc(sizeof(NODE));
 pNew->date = val;
 PNODE q = p->pNext;
    p->pNext = pNew;
 pNew->pNext = q;
 return true;

}

bool delete_list(PNODE pHead,int pos, int * pval)
{
 int i = 0;
 PNODE p = pHead;
 while(NULL != p->pNext && i<pos-1)
 {
  p = p->pNext;
  ++i;
 }

 if(NULL == p->pNext && i>pos-1)
  return false;
 *pval = p->pNext->date ;
 PNODE q =p->pNext;
 p->pNext = p->pNext->pNext;
 free(q);
 q = NULL;
 return false;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值