Swap Nodes in Pairs

来源:互联网 发布:ubuntu16 安装mysql 编辑:程序博客网 时间:2024/06/05 02:58
/** * 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 newHead = new ListNode(0);    newHead.next = head;    ListNode pre = newHead;    while(null != pre.next && null != pre.next.next){        ListNode firstNode = pre.next;        ListNode secondNode = pre.next.next;        firstNode.next = secondNode.next;        secondNode.next = firstNode;        pre.next = secondNode;        pre = firstNode;    }        return newHead.next;    }}
0 0