题目: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; } }