單向鏈錶的刪除操作

6 篇文章 0 订阅
4 篇文章 0 订阅
//單向鏈錶
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct link *addnote();
int delt(struct link *head);
int out(int i,struct link *head);
struct link
{
	int data;
	struct link *next;
};
int main()
{
	int i,j = 0;
	struct link *head = NULL;

	printf("請問要建立幾個結點:");
	scanf("%d",&i);
	printf("\n");
	while(i > 0)
	{
		head = addnote(head);
		i--;
		j++;
	}
	out(j,head);
    delt(head);
	out(j-1,head);
}
int delt(struct link *head)
{
    int i;
    char asw[5] = "0";
	struct link *pr = head,*q;
	printf("\n是否需要刪除節點?(Yeah / No)\n");\
	scanf("%s",asw);
	if(strcmp(asw,"Yeah") == 0)
	{
		printf("請問需要刪除第幾個節點(輸入序號): ");
		scanf("%d",&i);
		while(i-2 > 0)
		{
			pr = pr -> next;
		}//找到這個指針的前一個節點
		//第一次指向第二個節點,所以要循環i-2次
		q = pr -> next;
		pr -> next = pr -> next -> next;
		free(q);
	}
	return 0;
}
struct link *(addnote(struct link *head))
{
	int data;
	struct link *p =NULL,*pr = head;
	p = (struct link*)malloc(sizeof(struct link));
	if(head == NULL)
	{
		head = p;
	}
	else
	{
		while(pr -> next != NULL)
		{
			pr = pr -> next;
		}
		pr -> next = p;
	}//如果頭節點不是空節點,在尾節點與頭節點之間添加節點
	printf("請輸入數據:");
	scanf("%d",&data);//第一次是在頭節點中輸入數據
	p -> data = data;
	p -> next = NULL;//第一次p移動頭節點的下一位添加尾節點
	return head;
}
int out(int i,struct link *head)
{
    int j = 1;
    struct link *p = head;
    printf("\n");
    while(i > 0)
    {
        printf("第%d個數據為%d\n",j,p -> data);
        p = p -> next;
        i--;
        j++;
    }
    return 0;
}

運行結果:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值