Leetcode 24. Swap Nodes in Pairs

来源:互联网 发布:数据校验方式 编辑:程序博客网 时间:2024/05/26 12:53

leetcode 24. Swap Nodes in Pairs


/** * 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) {        ListNode p = new ListNode(-1);        p.next = head;        ListNode ans = p;        ListNode s = head;        if(s==null) return head;  // ==0        if(s.next==null) return head;//==1        ListNode f = head.next;        while(f!=null){  // two pointer            if((f.next!=null&&f.next.next==null ||f.next==null)) {                p.next = f;                s.next = f.next;                f.next = s;                break;            }            ListNode sNew = f.next;            ListNode fNew = sNew.next;            p.next = f;            f.next = s;            s.next = sNew;            p = s;            s = sNew;            f = fNew;        }        return ans.next;    }}


0 0
原创粉丝点击