Swap Nodes in Pairs(链表操作)
2024-08-31 06:18:23
Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed
思路:
1.(头二个节点已经事先处理)找出要换位置的两个节点的前驱节点,设为tempHead,设要更换的两个节点为p,q
2.那么直接p节点拿出,tempHead->next=q;p->next=NULL;
3.然后就是普通把p几点插入到q节点后面即可。p->next=q->next;q->next=p;
4.最后把暂时头部节点后移两个位置,进行下一次更换。
图解如下:
代码:
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode* res;
if(head==NULL) return NULL;
if(head->next==NULL) return head;
//交换第一,二个节点
ListNode* first=head->next;
head->next=first->next;
first->next=head; ListNode* tempHead=first->next;
ListNode* p;
ListNode* q;
while (tempHead)
{
if(tempHead->next!=NULL&&tempHead->next->next!=NULL){
p=tempHead->next;
q=tempHead->next->next;
}
else return first; tempHead->next=q;
p->next=NULL;//中间节点插入即可 p->next=q->next;
q->next=p;
tempHead=q->next; }
return first;
}
};
最新文章
- 深度解析C语言int与unsigned int
- HandlerThread 创建一个异步的后台线程
- AOP实现原理
- TypeC一个微软开发的超简单.NET依赖注入/IoC容器
- ODBC接口规范
- PHP生成随机字符串包括大小写字母
- python学习第三天第一部分
- virtualbox共享文件夹无访问权限问题解决方法
- java与数据结构(3)---java实现循环链表
- QF——OC中的KVC,KVO
- deepin2014.1安装搜狗后却找不到图标及配置
- Sublime 3 打造成 Python/Django IDE开发利器
- 四.RabbitMQ之发布/订阅(Publish/Subscribe)
- hadoop+hive+spark搭建(二)
- 如何在eclipse中添加ADT
- Flask的Windows部署:mod_wsgi + Apache
- 一、Tableau基础
- 【python】bytes与字符串的相互转化
- [转]XSS的原理分析与解剖:第四章(编码与绕过)
- Java transient关键字的理解