构建链表、输出链表元素、删除链表…

#include
#include

struct LNode
{
 int data;
 struct LNode * next;
}LNode;//链表结点

struct LNode * SetChain(){
    struct LNode * head;
 struct LNode * p1;
 struct LNode * p2;
 int n=0,num;
 p1=(struct LNode*)malloc(sizeof(struct LNode));
 head=p1;
 head->data=NULL;
 head->next=NULL;
 printf("请输入您要构建的链表结点的个数:");
    scanf("%d",&num);
 if(num>0)
  printf("请输入链表中的元素:");
 while(n
 {
  p1=(struct LNode*)malloc(sizeof(struct LNode));
  scanf("%d",&p1->data);  
  if(n==0)
  {
   p2=p1;
   head->next=p1;
  }
  else
  {
   p2->next=p1;
      p2=p1;
  }
  p2->next=NULL;
  n++;
 }
 return head;
}//构建一个链表

void ShowChain(struct LNode * head)
{
 struct LNode * p1;
 p1=head;
 if(p1->next==NULL)
  printf("该链表为空!");
 else
 {
  printf("该链表为:");
  do
  {
   p1=p1->next;
   printf("%d ",p1->data);
  }while(p1->next!=NULL);
  printf("\n");
 }
}//输出链表

struct LNode * DeletChain(struct LNode * head)
{
 struct LNode * p1;
 struct LNode * p2;
 int data1;
 p2=head;
 printf("\n请输入你要删除的结点:");
 scanf("%d",&data1);
 if(head->next==NULL)
  printf("链表为空,删除失败!");
 else
 {
  p1=head->next;
  while(p1->data!=data1&&p1->next!=NULL)
  {
   p2=p1;
   p1=p1->next;
  }
  if(data1==p1->data)
  {
   printf("已经删除结点:%d\n",p1->data);
   p2->next=p1->next;
  }
  else
   printf("该链表中没有输入的结点!\n");
 }
 return head;
}//删除链表中的一个结点

struct LNode * InvertChain(struct LNode * head)
{
 struct LNode * p1;
 struct LNode * p2;
 p1=head->next;
 head->next=NULL;
 while(p1)
 {
  p2=p1;
  p1=p1->next;
  p2->next=head->next;
  head->next=p2;
 }
 return head;
}//逆置链表


int main()
{
 struct LNode * L;
 L=SetChain();
 ShowChain(L);
 DeletChain(L); 
 ShowChain(L);
 InvertChain(L);
 ShowChain(L);
 return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值