24. Swap Nodes in Pairs-节点交换|指针

来源:互联网 发布:安卓pad应用推荐 知乎 编辑:程序博客网 时间:2024/05/01 12:49
原题链接:24. Swap Nodes in Pairs 

【思路】

本题考查节点的基本操作。每轮循环,如果存在2个节点,则交换前后位置,用p、q两个指针来完成;如果只存在1个节点,则不交换前后位置:

public class Solution {    public ListNode swapPairs(ListNode head) {        ListNode p = new ListNode(0), q = head, re = p;        p.next = head;        while((q = p.next) != null && q.next != null) {            p.next = q.next;            q.next = p.next.next;            p.next.next = q;            p = q;        }        return re.next;    }}
55 / 55 test cases passed. Runtime: 0 ms  Your runtime beats 13.35% of javasubmissions.

1 0