LeetCode - Swap Nodes in Pairs - Frequent

来源:互联网 发布:浙江省数据库三级 编辑:程序博客网 时间:2024/06/05 20:10

https://leetcode.com/problems/swap-nodes-in-pairs/

这种题都可以用dummy node来解决,不过要注意其中node指针换来换去的细节问题,很容易错。

代码如下:

public class Solution {    public ListNode swapPairs(ListNode head) {        if(head==null || head.next == null) return head;                ListNode dummy = new ListNode(0);        ListNode traverse = dummy;                while(head!=null && head.next!=null){            ListNode tmp = head.next.next;            traverse.next = head.next;            head.next.next = head;            traverse = head;            head = tmp;        }        traverse.next = head;        return dummy.next;    }}


0 0