单链表的操作

创建

while(cin>>n&&n!=-1)
{
		newnode = new node;
		newnode->next = NULL;
		newnode->v = n;
		if (head==NULL)
		{
			head = newnode;
			tail = newnode;
		}
		else
		{
			tail->next = newnode;
			tail = newnode;
		}
}

遍历

void show()
{
	node* s = head;
	while (s != NULL)
	{
		printf("%d ", s->v);
		s = s->next;
	}
}

删除

bool Delete(int i)
{
	node* p, *t;
	int j;
	if (head == NULL)
	{
		printf("链表为空\n");
		return false;
	}
	if (i == 1)
	{
		p = head;
		head = head->next;
		delete[]p;
	}
	else
	{
		j = 1;
		t = head;
		while (t != NULL && j < i - 1)
		{
			t = t->next;
			j += 1;
		}
		if (t->next == NULL||i<1)
		{
			printf("越界\n");
		}
		else
		{
			p = t->next;
			t->next = p->next;
			delete[]p;
		}
	}
	return true;
}

插入

void insert(int x, int index)
{
	node* newnode = new node;
	newnode->next = NULL;
	newnode->v = x;
	if (index == 1)
	{
		newnode->next = head;
		head = newnode;
	}
	else
	{
		int j = 1;
		node* t = head;
		while (t != NULL && j < index - 1)
		{
			j++;
			t = t->next;
		}
		if (t == NULL || index < 1)
		{
			printf("越界\n");
		}
		else
		{
			newnode->next = t->next;
			t->next = newnode;
		}
	}
}

完整代码

#include<iostream>
using namespace std;
struct node
{
	int v;
	struct node* next;
};
node* head=NULL,* tail=NULL;
bool Delete(int i)
{
	node* p, *t;
	int j;
	if (head == NULL)
	{
		printf("链表为空\n");
		return false;
	}
	if (i == 1)
	{
		p = head;
		head = head->next;
		delete[]p;
	}
	else
	{
		j = 1;
		t = head;
		while (t != NULL && j < i - 1)
		{
			t = t->next;
			j += 1;
		}
		if (t->next == NULL||i<1)
		{
			printf("越界\n");
		}
		else
		{
			p = t->next;
			t->next = p->next;
			delete[]p;
		}
	}
	return true;
}
void show()
{
	node* s = head;
	while (s != NULL)
	{
		printf("%d ", s->v);
		s = s->next;
	}
}
void insert(int x, int index)
{
	node* newnode = new node;
	newnode->next = NULL;
	newnode->v = x;
	if (index == 1)
	{
		newnode->next = head;
		head = newnode;
	}
	else
	{
		int j = 1;
		node* t = head;
		while (t != NULL && j < index - 1)
		{
			j++;
			t = t->next;
		}
		if (t == NULL || index < 1)
		{
			printf("越界\n");
		}
		else
		{
			newnode->next = t->next;
			t->next = newnode;
		}
	}
}
int main(void)
{
	int n;
	node* newnode;
	while(cin>>n&&n!=-1)
	{
		newnode = new node;
		newnode->next = NULL;
		newnode->v = n;
		if (head==NULL)
		{
			head = newnode;
			tail = newnode;
		}
		else
		{
			tail->next = newnode;
			tail = newnode;
		}
	}
	show();
	printf("\n");
	Delete(5);
	show();
	printf("\n");
	insert(11,5);
	show();
	printf("\n");
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我还是忘不了

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值