File tree Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Expand file tree Collapse file tree 1 file changed +51
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode id=24 lang=java
3
+ *
4
+ * [24] Swap Nodes in Pairs
5
+ *
6
+ * https://leetcode.com/problems/swap-nodes-in-pairs/description/
7
+ *
8
+ * algorithms
9
+ * Medium (43.23%)
10
+ * Total Accepted: 283.3K
11
+ * Total Submissions: 655.4K
12
+ * Testcase Example: '[1,2,3,4]'
13
+ *
14
+ * Given a linked list, swap every two adjacent nodes and return its head.
15
+ *
16
+ * You may not modify the values in the list's nodes, only nodes itself may be
17
+ * changed.
18
+ *
19
+ *
20
+ *
21
+ * Example:
22
+ *
23
+ *
24
+ * Given 1->2->3->4, you should return the list as 2->1->4->3.
25
+ *
26
+ *
27
+ */
28
+ /**
29
+ * Definition for singly-linked list. public class ListNode { int val; ListNode
30
+ * next; ListNode(int x) { val = x; } }
31
+ */
32
+ class Solution {
33
+ public ListNode swapPairs (ListNode head ) {
34
+ if (head == null || head .next == null ) {
35
+ return head ;
36
+ }
37
+ ListNode dummy = new ListNode (0 );
38
+ dummy .next = head ;
39
+ ListNode prev = dummy ;
40
+ while (prev .next != null && prev .next .next != null ) {
41
+ ListNode a = prev .next ;
42
+ ListNode b = a .next ;
43
+ ListNode c = b .next ;
44
+ prev .next = b ;
45
+ b .next = a ;
46
+ a .next = c ;
47
+ prev = a ;
48
+ }
49
+ return dummy .next ;
50
+ }
51
+ }
You can’t perform that action at this time.
0 commit comments