IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 数据结构与算法 -> 力扣 C++ 链表结点两两交换 -> 正文阅读

[数据结构与算法]力扣 C++ 链表结点两两交换

#include<iostream>
using namespace std;
typedef struct node
{
	int data;
	node* next;
};
class List
{
private:
	node* head;
	node* last;
public:
	List()//initialize linked list(初始化链表)
	{
		head = new node;
		head->next = NULL;
		last = head;
	}
	void CreateList(int a[], int length)
	{
		for (int i = 0; i < length; ++i)
		{
			node* temp = new node;
			temp->data = a[i];
			last->next = temp;
			last = temp;
		}
		last->next = NULL;
	}
	void DisplayList()
	{
		if (head->next == NULL)
			return;
		for (node* p = head->next; p; p = p->next)
			cout << p->data << '\t';
		cout << endl;
	}
	void Swap()
	{
		if (head->next == NULL || head->next->next == NULL)
			return;
		//set the two pointer p and q to point to the front and the back node of the data field respectively,and then make the next node of the head node point to null
		//设置p,q两个指针分别指向数据域的前后两个结点,再令头结点的下一个结点指向空
		node* p = head->next;
		node* q;
		head->next = NULL;
		node *last = head;
		while (p)
		{
			q = p->next;
			//when it is odd,the last node is directly connected
			//当为奇数时,直接连接最后一个结点
			if (q == NULL)
			{
				last->next = p;
				last = p;
				last->next = NULL;
				return;
			}
			last->next = q;
			last = q;
			//at this time ,the first node address of the node to be exchanged must be recorded,otherwise the address will be lost
			//此时一定要记录下一个要交换结点的首结地址不然地址丢失
			node* temp;
			 temp=q->next;
			last->next = p;
			last = p;
			last->next = NULL;
			p = temp;
		}
		
	}
};
int main()
{
	int a[6] = { 1,2,3,4,5,6};
	List list;
	list.CreateList(a, 6);
	cout << "链表未交换结点前结果" << endl;
	list.DisplayList();
	cout << "链表交换结点后结果" << endl;
	list.Swap();
	list.DisplayList();
}

?

?

  数据结构与算法 最新文章
【力扣106】 从中序与后续遍历序列构造二叉
leetcode 322 零钱兑换
哈希的应用:海量数据处理
动态规划|最短Hamilton路径
华为机试_HJ41 称砝码【中等】【menset】【
【C与数据结构】——寒假提高每日练习Day1
基础算法——堆排序
2023王道数据结构线性表--单链表课后习题部
LeetCode 之 反转链表的一部分
【题解】lintcode必刷50题<有效的括号序列
上一篇文章      下一篇文章      查看所有文章
加:2021-08-09 10:28:44  更:2021-08-09 10:30:32 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年5日历 -2024/5/19 20:53:25-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码