单链表的建立、测长、打印、删除节点、插入节点

单链表的操作注意事项:

1)输入链表头节点检验是否为空;

2)链表的遍历注意要前一节点的保存,以便插入或删除操作;

 3)循环条件中注意p->next!=NULL条件使用。

#include<iostream>
using namespace std;

typedef struct node
{
	int data;
	node *next;
}node;

node *Creat()
{
	node *head,*p,*s;
	int x;
	head=(node *)malloc(sizeof(node));
	p=head;
	int cycle=1;
	while(cycle)
	{

		cout<<"请输入一个数:"<<endl;
		cin>>x;
		if (x!=0)
		{
			s=(node *)malloc(sizeof(node));
			s->data=x;
			p->next=s;
			p=s;
		}
		else
		{
			p->next=NULL;
			cycle=0;
		}
	}
	head=head->next;
	return head;
}

int length(node *head)
{
	int n=0;
	node *p;
	p=head;
	while (p!=NULL)
	{
		n++;
		p=p->next;
	}
	return n;
}

void print(node *head)
{
	node *p;
	p=head;
	int n;
	n=length(head);
	cout<<"链表中有"<<n<<"个记录!"<<endl;
	if (p!=NULL)
	{
		while (p!=NULL)
		{
			cout<<p->data<<" ";
			p=p->next;
		}
	}
}

node *del(node *head,int num)
{
	node *p,*s;
	p=head;
	while (p->data!=num&&p->next!=NULL)
	{
		s=p;
		p=p->next;
	}
	if (num==p->data)
	{
		if(p==head)
		{
			p=p->next;
			head=p;
			free(p);
		}
		else
		{
			s->next=p->next;
			free(p);
		}

	}
	else
		cout<<"没有找到"<<num<<endl;
	return head;
}

node *insert(node *head,int num)
{
	node *p,*s,*n;
	p=head;
	n=(node *)malloc(sizeof(node));
	n->data=num;
	while (num>p->data&&p!=NULL)
	{
		s=p;
		p=p->next;
	}
	if (num<=p->data)
	{
		if (head==p)
		{
			n->next=p;
			head=n;
		}
		else
		{
			n->next=p;
			s->next=n;
		}
	}
	else
	{
		p->next=n;
		n->next=NULL;
	}

	return head;
	
}
void main()
{
	node *head=Creat();
	print(head);
//	del(head,3);
	head=insert(head,4);
	print(head);
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值