File tree Expand file tree Collapse file tree 3 files changed +86
-0
lines changed Expand file tree Collapse file tree 3 files changed +86
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for singly-linked list.
3
+ * struct ListNode {
4
+ * int val;
5
+ * ListNode *next;
6
+ * ListNode() : val(0), next(nullptr) {}
7
+ * ListNode(int x) : val(x), next(nullptr) {}
8
+ * ListNode(int x, ListNode *next) : val(x), next(next) {}
9
+ * };
10
+ */
11
+ class Solution {
12
+ public:
13
+ ListNode* swapPairs (ListNode* head) {
14
+ if (head == NULL || head->next == NULL ) {
15
+ return head;
16
+ }
17
+
18
+ ListNode* d = new ListNode (0 , head);
19
+ ListNode* a = d;
20
+ ListNode* b = d->next ;
21
+
22
+ while (b != NULL && b->next != NULL ) {
23
+ a->next = b->next ;
24
+ b->next = a->next ->next ;
25
+ a->next ->next = b;
26
+ b = b->next ;
27
+ a = a->next ->next ;
28
+ }
29
+
30
+ return d->next ;
31
+ }
32
+ };
Original file line number Diff line number Diff line change
1
+ package main
2
+
3
+ /**
4
+ * Definition for singly-linked list.
5
+ * type ListNode struct {
6
+ * Val int
7
+ * Next *ListNode
8
+ * }
9
+ */
10
+ func swapPairs (head * ListNode ) * ListNode {
11
+ if head == nil || head .Next == nil {
12
+ return head
13
+ }
14
+
15
+ d := & ListNode {Val : 0 , Next : head }
16
+ a := d
17
+ b := d .Next
18
+
19
+ for b != nil && b .Next != nil {
20
+ a .Next = b .Next
21
+ b .Next = a .Next .Next
22
+ a .Next .Next = b
23
+ a = a .Next .Next
24
+ b = b .Next
25
+ }
26
+
27
+ return d .Next
28
+ }
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for singly-linked list. public class ListNode { int val; ListNode next; ListNode() {}
3
+ * ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val;
4
+ * this.next = next; } }
5
+ */
6
+ class Solution {
7
+ public ListNode swapPairs (ListNode head ) {
8
+ if (head == null || head .next == null ) {
9
+ return head ;
10
+ }
11
+ ListNode d = new ListNode ();
12
+ d .next = head ;
13
+ ListNode a = d ;
14
+ ListNode b = d .next ;
15
+
16
+ while (b != null && b .next != null ) {
17
+ a .next = b .next ;
18
+ b .next = a .next .next ;
19
+ a .next .next = b ;
20
+ a = a .next .next ;
21
+ b = b .next ;
22
+ }
23
+
24
+ return d .next ;
25
+ }
26
+ }
You can’t perform that action at this time.
0 commit comments