24 Swap Nodes in Pairs

来源:互联网 发布:武侠大宗师源码外网 编辑:程序博客网 时间:2024/05/21 17:30

题目链接:https://leetcode.com/problems/swap-nodes-in-pairs/

题目:

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.

解题思路:
每两个节点作为一组,交换组内的两个节点。比较简单,面试比较少考链表操作。。。

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode swapPairs(ListNode head) {        if(head == null)            return head;        ListNode headNode = new ListNode(0);        headNode.next = head;        ListNode p = headNode;        while(p.next != null && p.next.next != null) {            ListNode temp = p.next.next;            p.next.next = temp.next;            temp.next = p.next;            p.next = temp;            p = p.next.next;        }        return headNode.next;    }}
55 / 55 test cases passed.Status: AcceptedRuntime: 328 ms
0 0