链表的基本操作

10 篇文章 0 订阅
7 篇文章 0 订阅
#include <stdio.h>
#include <malloc.h>

typedef struct list{
	int value;
	struct list *next;
}node;

node* add(node *head)    //增加节点
{
	node *p = head, *p2;
	int tmp;
	char ch;
	scanf("%d", &tmp);
	ch = getchar();
	p2 = (node *)malloc(sizeof(node));
	p2->value = tmp;
	p2->next = NULL;
	if (NULL == p)
		return p2;

	while (p->next != NULL)
		p = p->next;

	p->next = p2;
	return head;
}

node* del(node *head)    //删除节点
{
	int tmp, flag;
	char ch;
	node *p = head, *pre = NULL;
	if (NULL == p)
	{
		printf("ERROR! List is NULL!\n");
		return head;
	}

	scanf("%d", &tmp);
	ch = getchar();
	flag = 0;

	while (p)
	{
		if (p->value == tmp)
		{
			flag = 1;
			break;
		}

		pre = p;
		p = p->next;
	}

	if (0 == flag)
	{
		printf("ERROR! There is no %d.\n", tmp);
		return head;
	}

	if(NULL == pre)
	{
		p = p->next;
		free(head);
		return p;
	}

	pre->next = p->next;
	free(p);
	return head;
}

void print(node *head)    //遍历链表
{
	node *p = head;
	while (p)
	{
		printf("%d\t", p->value);
		p = p->next;
	}

	printf("\n");
	return;
}

node *rev(node *head)    //翻转链表
{
	node *p = head, *pre = NULL, *tmp;
	while (p)
	{
		tmp = p;
		p = p->next;
		tmp->next = pre;
		pre = tmp;
	}

	return pre;
}

int main()
{
	char c, ch;
	node *head = NULL;
	printf("a:增加节点;\td:删除节点;\tp:遍历链表;\tr:翻转链表.\n");
	while (scanf("%c", &c) != EOF)
	{
		ch = getchar();
		switch (c)
		{
		case 'a': head = add(head); break;
		case 'd': head = del(head); break;
		case 'p': print(head); break;
		case 'r': head = rev(head); break;
		default: printf("Invalid input!\n");
		}

		printf("a:增加节点;\td:删除节点;\tp:遍历链表;\tr:翻转链表.\n");
	}

	return 0;
}



	

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值