C-链表

本文介绍了一个使用C语言实现的链表基本操作示例,包括创建、插入和删除节点等功能,并通过用户交互方式演示了这些操作的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


上图为效果图

#include <stdio.h>

#include <stdlib.h>
#include <malloc.h>
typedef  struct  Node
 {      int   data;
        struct  Node  *next;
 } SLIST;
 void inlist(SLIST *l,int a)
 {
   SLIST *p,*q;
   int i;
   p=(SLIST *)malloc(sizeof(SLIST));
   l->next=p;
    for(i=a;i>0;--i)
	{
		q=(SLIST *)malloc(sizeof(SLIST));
	       	printf("请输入数字\n");
			scanf("%d",&p->data);
		p->next=q;                                           /*这儿看看*/
		p=q;
	}
    q->next=NULL;
 }
 void Inset(SLIST *l,int i,int e)
{
	 SLIST *p,*s;
	 int j;
     p=l;
	 j=0;
   while(p&&j<i-1)
   {
	   p=p->next;
	             
	    s=(SLIST *)malloc(sizeof(SLIST));
	    s->data=e;
	    s->next=p->next;                                    /*这儿看看 链表的插入*/
	    p->next=s;
   }
}
void OutputList(SLIST *h)
{    SLIST  *p;
      p=h->next;
      if(p==NULL)     printf("The list is NULL!\n");
      else
      {     printf("Head");
            while((p->next)!=NULL)
            {      printf("->%d",p->data);
                    p=p->next;
             }
             printf("->End\n");
      }
}


void Delete(SLIST *l,int i)
{
    SLIST *p;
   int j;
     p=l;
	 j=0;
	 while(p->next&&j<i-1)
	 {
		 p=p->next;
		 ++j;
		 p->next=p->next->next;
	 }
}
int main()
{
     SLIST *h;
	 int i,j,k,m,n;
	 h= (SLIST *)malloc(sizeof(SLIST));
	 printf("输入要求的长度\n");
	 scanf("%d",&i);
 	 inlist(h, i);
 	  OutputList(h);
 	 printf("输入数字,1代表删除,2代表插入\n");
 	 scanf("%d",&n);
 	 while(n!=1||n!=2)
 	 {
 	     if(n==1)
        {
            printf("输入删除的位置\n");
 	        scanf("%d",&j);
 	        Delete(h,j);
 	        OutputList(h);
        }
 	    else if(n==2)
 	    {
 	        printf("输入插入的位置与值\n");
 	        scanf("%d%d",&k,&m);
 	        Inset(h,k,m);
 	         OutputList(h);
 	    }
 	     printf("再次输入数字,1代表删除,2代表插入\n");
 	        scanf("%d",&n);
 	 }
     OutputList(h);
	  return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值