其他分享
首页 > 其他分享> > Leetcode24.两两交换链表中的节点

Leetcode24.两两交换链表中的节点

作者:互联网

题目:24.两两交换链表中的节点

思路:链表交换

代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null) return head;
        ListNode pre, fir, sec, t;
        pre = t = null;
        sec = head;
        fir = head.next;
        if(fir == null) return head;
        while(fir != null && sec != null){
            sec.next = fir.next;
            fir.next = sec;
            if(pre == null){
                head = fir;
            }else{
                pre.next = fir;
            }
            pre = sec;
            sec = pre.next;
            fir = sec == null ? null : sec.next;
        }
        return head;
    }
}

 

标签:fir,head,ListNode,next,链表,sec,Leetcode24,null,节点
来源: https://www.cnblogs.com/liuyongyu/p/14187688.html