C++链表操作

C++链表操作

1.链表的冒泡排序

2.翻转链表

3.查找链表中间节点

4.删除倒数第K个链表

操作效果如下

aa

 

 

 

 

 

 

代码

#include <iostream>
#include <algorithm>
using namespace std;

void bubble_sort(int a[], int N)
{
	int i = N - 1;
	while (i > 0)
	{
		int lastex = 0;
		for (int j = 0; j < i; j++)
		{
			if (a[j]>a[j + 1])
			{
				swap(a[j], a[j + 1]);
				lastex = j;
			}
		}
		i = lastex;
	}
}

struct Node{
	int data;
	Node *next;
};

int main()
{
	int arr[] = { 4, 3, 5, 2, 1 };
	
	//插入链表
	Node *head, *prev;
	head = NULL;
	prev = head;
	for (int i = 0; i < 5; i++)
	{
		Node *temp = new Node;
		temp->data = arr[i];
		temp->next = NULL;
		if (head == NULL)
			head = temp;
		else
			prev->next = temp;
		prev = temp;
	}
	cout << "原始链表-----" << endl;
	Node *cur = head;
	while (cur != NULL)
	{
		cout << cur->data << "-";
		cur = cur->next;
	}
	cout << endl;

	//冒泡排序
	Node *end = NULL;
	while (end != head)
	{
		cur = head;
		while (cur->next != end)
		{
			if (cur->data > cur->next->data)
			{
				int temp = cur->next->data;
				cur->next->data = cur->data;
				cur->data = temp;
			}
			cur = cur->next;
		}
		end = cur;
	}
	
	cout << "冒泡排序后-----" << endl;
	cur = head;
	while (cur != NULL)
	{
		cout << cur->data << "-";
		cur = cur->next;
	}
	cout << endl;

	//翻转链表
	Node *new_head = NULL;
	while (head != NULL)
	{
		cur = head;
		head = head->next;

		if (new_head == NULL)
		{
			new_head = cur;
			new_head->next = NULL;
		}
		else
		{
			cur->next = new_head;
			new_head = cur;
		}
	}
	head = new_head;

	cout << "翻转链表后-----" << endl;
	cur = head;
	while (cur != NULL)
	{
		cout << cur->data << "-";
		cur = cur->next;
	}
	cout << endl;

	//查找中间节点
	Node *fast, *slow;
	fast = slow = head;
	while (fast->next != NULL)
	{
		fast = fast->next->next;
		slow = slow->next;
	}
	cout << "中间节点-----" << endl;
	cout << slow->data << endl;

	//删除倒数第k=3个节点
	Node *front, *back;
	front = back = head;
	front = front->next->next;
	while(front->next != NULL)
	{
		front = front->next;
		back = back->next;
	}
	back->data = back->next->data;
	Node *del = back->next;
	back->next = back->next->next;	
	delete del;
	del = NULL;

	cout << "删除倒数第k=3个节点后-----" << endl;
	cur = head;
	while (cur != NULL)
	{
		cout << cur->data << "-";
		cur = cur->next;
	}
	cout << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值