-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwapNodesinPairs.java
More file actions
37 lines (34 loc) · 1.04 KB
/
SwapNodesinPairs.java
File metadata and controls
37 lines (34 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package medium;
import util.ListNode;
import static util.Utils.*;
/**
*
* ClassName: SwapNodesinPairs
* @author chenyiAlone
* Create Time: 2018/12/10 10:59:40
* Description: No.24
*/
public class SwapNodesinPairs {
public ListNode swapPairs(ListNode head) {
if (head == null) return head;
ListNode first = head, second = head.next;
ListNode ans = new ListNode(0), temp = ans;
while (first != null) {
if (second == null) {
temp.next = new ListNode(first.val);
break;
}
temp.next = new ListNode(second.val);
temp = temp.next;
temp.next = new ListNode(first.val);
temp = temp.next;
first = second.next;
if (first != null) second = first.next;
}
return ans.next;
}
public static void main(String[] args) {
ListNode list = initListNode();
System.out.println(new SwapNodesinPairs().swapPairs(list));
}
}