LeetCode_24_Swap Nodes in Pairs

来源:互联网 发布:模拟电路软件汉化版 编辑:程序博客网 时间:2024/05/18 22:42

题目描述

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.

个人感想

操作链表的时候完全可以建一个新的头结点,这样在处理边界问题的时候非常方便

代码实现

class Solution {    public ListNode swapPairs(ListNode head) {        if (head == null)             return null;        if (head.next == null)            return head;        ListNode fakeHead = new ListNode(0);        fakeHead.next = head;        ListNode currentNode = fakeHead;        while (currentNode.next != null && currentNode.next.next != null) {            ListNode first = currentNode.next;            ListNode second = currentNode.next.next;            first.next = second.next;            second.next = first;            currentNode.next = second;            currentNode = currentNode.next.next;        }        return fakeHead.next;    }}