leetcode Swap Nodes in Pairs
来源:互联网 发布:c 语言主要应用领域 编辑:程序博客网 时间:2024/05/22 00:40
两两交换节点,如下
Given 1->2->3->4
, you should return the list as 2->1->4->3
.
我的思路是每次处理2个,即1和2交换完后,再对3和4操作。
注意点:如果3和4交换了,那么此时1应该指向4而不是3,即要加入plast
可能在末尾仅剩1个,即无需再交换,需要加if(pright==NULL) break;
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* swapPairs(struct ListNode* head) { struct ListNode *pleft,*pright,*new_head,*plast; if(head==NULL||head->next==NULL) //若无节点或仅一个节点,直接返回 return head; pleft=head; //左节点 new_head=pleft->next; //新头节点一定是左节点的下一个 plast=NULL; //刚开始没有上一个节点,置为NULL while(pleft!=NULL) { pright=pleft->next; //右节点 if(pright==NULL) //如果右节点为空,说明到尾了,退出 break; //否则开始交换操作 if(plast!=NULL) plast->next=pright; //如果发生交换,那么上一节点一定会指向右节点 pleft->next=pright->next; //左节点指向右节点的下一个 pright->next=pleft; //右节点指向左节点 //交换操作结束 plast=pleft; //设置上一节点 pleft=pleft->next; //开始处理后面2个 } return new_head;}
0 0
- LeetCode:Swap Nodes in Pairs
- LeetCode: Swap Nodes in Pairs
- [Leetcode] Swap Nodes in Pairs
- LeetCode : Swap Nodes in Pairs
- [LeetCode] Swap Nodes in Pairs
- Leetcode: Swap nodes in pairs
- [LeetCode]Swap Nodes in Pairs
- [LeetCode]Swap Nodes in Pairs
- LeetCode-Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- LeetCode | Swap Nodes in Pairs
- 【leetcode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- LeetCode - Swap Nodes in Pairs
- 【LeetCode】Swap Nodes in Pairs
- Leetcode: Swap Nodes in Pairs
- Leetcode Swap Nodes in Pairs
- LeetCode Swap Nodes in Pairs
- 《Qt》part 5 Qt5.5.0串口通信
- Android 下拉刷新SwipeRefreshLayout
- 数据库常见笔试面试题
- Java开发中的23种设计模式之结构型模式
- Android内存机制分析上篇:了解Android堆和栈
- leetcode Swap Nodes in Pairs
- json格式HttP数据提交解析
- (十五)洞悉linux下的Netfilter&iptables:开发自己的hook函数【实战】(上)
- Delete Node in a Linked List
- 字符串转数组
- 浅谈XML语言(三)
- Feature Scaling 特征缩放
- NO.4名词查寻器******完结
- 统计学习三要素:模型、策略、算法