Swap Nodes in Pairs

来源:互联网 发布:网红淘宝店前十名 编辑:程序博客网 时间:2024/06/05 00:55
/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode swapPairs(ListNode head) {        ListNode fakeHead = new ListNode(-1);        fakeHead.next = head;        head = fakeHead;        while(head.next != null && head.next.next != null){            swap(head);            head = head.next.next;        }        return fakeHead.next;    }        public void swap(ListNode node){        ListNode n1 = node.next;        ListNode n2 = node.next.next;        node.next = n2;        n1.next = n2.next;        n2.next = n1;    }}

0 0
原创粉丝点击