带头结点单链表操作(数据结构)

#include<iostream>
using namespace std;
typedef struct node
{
	int data;
	node *next;
}node;

node* create()                  //创建单链表,带头结点
{
	int i = 0;
	node *head, *p, *q;
	int x = 0;
	head = (node*)malloc(sizeof(node));
	q = head;

	while (1)
	{
		cout << "input data" << endl;
		cin >> x;
		if (x == 0)                          //输入为0的时候结束建立单链表
			break;
		p = (node*)malloc(sizeof(node));
		p->data = x;
		q->next = p;
		q = p;
	}
	q->next = NULL;
	return head;
}

int length(node* head)     //单链表长度
{
	int len = 0;
	node* p;
	p = head->next;
	while (p != NULL)
	{
		len++;
		p = p->next;
	}
	return len;
}

void print(node* head)           //输出单链表
{
	node* p;
	int index = 0;
	if (head->next == NULL)
	{
		cout << "Link is empty" << endl;
	}
	p = head->next;
	while (p != NULL)
	{
		cout << "the node is" << p->data << endl;
		p = p->next;
	}
}

node* search(node* head, int pos)    //查找pos位置的结点
{
	node* p = head->next;
	if (pos < 0)
	{
		cout << "incorect position" << endl;
		return NULL;
	}
	if (p == NULL)
	{
		cout << "the link is empty" << endl;
		return NULL;
	}
	if (pos== 0)
		return head;
	while (--pos)
	{
		if ((p = p->next) == NULL)
		{
			cout << "incorrect position" << endl;
			break;
		}
	}
	return p;
}
node* insert(node* head, int pos, int data)
{
	node* item = NULL;
	node* p;
	item = (node*)malloc(sizeof(node));
	item->data = data;
	if (pos == 1)
	{
		head->next = item;
		return head;
	}
	p = search(head, pos);
	if (p != NULL)
	{
		item->next = p->next;
		p->next = item;
	}
	return head;
}

node* delete_(node*head, int pos)
{
	node* item = NULL;
	node* p = head->next;
	if (p == NULL)
	{
		cout << "link is empty" << endl;
	}
	p = search(head, pos-1);
	if (p != NULL && p->next != NULL)
	{
		item = p->next;
		p->next = item->next;
		delete item;
	}
	return head;
}


int main()
{
	node* head=create();
	cout << "length: " << length(head) << endl;
	head = insert(head, 2, 5);//在第二个结点(算上表头是第三个)之后插入5
	cout << "insert integer 5 after 2th node:" << endl;
	print(head);
	head = delete_(head, 2);
	cout << "after delete 3th node :" << endl;
	print(head);
    return 0;
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值