本文主要是介绍leetcode -- 24. Swap Nodes in Pairs,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
Given a linked list, swap every two adjacent nodes and return its head.
Example:
Given 1->2->3->4, you should return the list as 2->1->4->3.
Note:
Your algorithm should use only constant extra space.
You may not modify the values in the list’s nodes, only nodes itself may be changed.
如果可以改变节点的值的话就很简单了。
题目难度:Middle
AC代码
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/
class Solution {public ListNode swapPairs(ListNode head) {if(head == null || head.next == null) return head;ListNode newHead = new ListNode(0);ListNode curNode = newHead; ListNode temp;while(head != null && head.next != null){temp = head.next.next;curNode.next = head.next;curNode.next.next = head;head = temp;curNode = curNode.next.next;}//if(head != null) curNode.next = head; curNode.next = head; //这一句至关重要。没加的后果:奇数个结点不会出现问题,偶数个结点会使得最后两个结点互指。return newHead.next;}
}
这篇关于leetcode -- 24. Swap Nodes in Pairs的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!