单链表的创建、测长、打印、插入、排序、逆置

本文介绍了一个简单的链表实现,包括创建、打印、插入、排序、反转和删除节点等功能。通过具体的C++代码示例,展示了如何进行基本的链表管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <string>

using namespace std;
typedef struct qwer
{
	int data;
	struct qwer *next;
}node;
node *creat(int n)
{
	node *p, *s, *h;
	h = (node*)malloc(sizeof(node));
	p = h;
	int x;
	for (int i = 1; i <= n; i++)
	{
		s = (node*)malloc(sizeof(node));
		cout << "请输入第" << i<<"个数: " ;
		cin >> x;
		s->data = x;
		p->next = s;
		p = s;
	}
	p->next = NULL;
	return h;
}
int length(node *head)
{
	int n=0;
	node *p;
	p = head->next;
	while (p != NULL)
	{
		p = p->next;
		n++;
	}
	return n;
}
void print(node *head)
{
	node *p;
	p = head->next;
	if(head!=NULL)
	while (p != NULL)
	{
		cout << p ->data << endl;
		p = p ->next;
	}

}
void insert(node *head,int i,int num)
{
	node *p1,*insert;
	int j = 1;
	
	p1 = head;
	while (j<i)
	{
		p1 = p1->next;
		j++;
	}
	insert = (node*)malloc(sizeof(node));
	insert->data = num;
	insert->next = p1->next;
	p1->next = insert;
}
node *sort(node *head)
{
	node *p ;
	int temp,n;
	n = length(head);
	if (head == NULL || head->next == NULL)
	{
		return head ;
	}
	for (int i = 1; i < n; i++)
	{
		p = head->next;
		for (int j=0;j<n-i;j++)
		{
			if ((p->data) >(( p->next)->data))
			{
				temp = p->data;
				p->data = p->next->data;
				p ->next->data = temp;
			}
			p = p-> next;
		}
	}

}
void reverse(node *head)
{
	node *p,*q;
	p = head->next;
	head->next = NULL;
	
	while (p)
	{
		q = p;
		p = p->next;
		q->next=head->next;
		head->next = q;
	
	}


}
node *del(node* head, int num)
{
	node *p1, *p2;
	p1 = head;
	p2 = p1;
	while (num != p1->data&&p1->next != NULL)
	{
		p2 = p1;
		p1 = p1->next;
	}
	if (num == p1->data)
	{
		p2->next = p1->next;
		free(p1);
	}
	else
		cout << "no find" << endl;
	return head;
}
int main()
{
	while (1)
	{
	node *h;
	h = creat(5);
	cout << "length=" << length(h) << endl;

	print(h);
	
	cout << "-----------------" << endl;
	//sort(h);
	//insert(h, 1, 50);
	reverse(h);
	print(h);

	}

}




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值