38 lines
893 B
Java
38 lines
893 B
Java
/*
|
|
* @lc app=leetcode id=24 lang=java
|
|
*
|
|
* [24] Swap Nodes in Pairs
|
|
*/
|
|
|
|
// @lc code=start
|
|
/**
|
|
* 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) {
|
|
ListNode dummy = new ListNode(0);
|
|
dummy.next = head;
|
|
ListNode prev = dummy, cur = head, next = head == null ? null : head.next, t;
|
|
while(cur !=null && next != null) {
|
|
prev.next = next;
|
|
t = next.next;
|
|
next.next = cur;
|
|
cur.next = t;
|
|
|
|
prev = cur;
|
|
cur = cur.next;
|
|
next = cur == null ? null : cur.next;
|
|
}
|
|
return dummy.next;
|
|
}
|
|
}
|
|
// @lc code=end
|
|
|