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;
    }
}

 

上一篇:创建并操作循环链表


下一篇:基于MATLAB的数字信号处理(5) FIR数字滤波器设计及软件实现