[LeetCode]Swap Nodes in Pairs
来源:互联网 发布:mac版lol国服何时出 编辑:程序博客网 时间:2024/06/06 04:56
题目描述
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.
给你一个链表,交换相邻的两个链表解题思路
- 交换相邻两个链表节点,并将交换的尾节点记录;
- 将上次的尾节点指向本次交换后的头节点;
- 重复上述步骤;
以上需要注意如果节点个数为奇数的情况。
代码
public ListNode swapPairs(ListNode head) {ListNode node = head, result = head;ListNode firstNode = head;ListNode secondNode = head;ListNode lastNode = head;while (node != null) {firstNode = node;secondNode = node.next;if (secondNode == null) {//考虑节点个数为奇数的情况secondNode = node;} else {firstNode.next = secondNode.next;secondNode.next = firstNode;}if (firstNode == head) {//第一次交换时,记录最终交换完的头节点result = secondNode;} else {//上一次交换的尾节点指向本次交换完的头节点lastNode.next = secondNode;}lastNode = firstNode;node = firstNode.next;}return result;}
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
- 微信开发者功能
- RHEL(redhat 5.x,6.x)和CentOS上Gitlab安装全过程
- 开方数 时间限制:500 ms | 内存限制:65535 KB 难度:3
- 海康威视笔试试题(DSP/嵌入式)
- js中获得当前时间是年份和月份
- [LeetCode]Swap Nodes in Pairs
- touch
- 浅谈BST (Binary Search Tree)
- 微信公众平台群发规则说明
- linux驱动工程面试必问知识点
- 一个射频工程师应该知道的
- ASCII码十六进制转换表
- 设置累计天数
- HDU How Many Tables