Skip to content

Commit c6bd237

Browse files
committed
add q24 java, cpp, go
1 parent 6bf6fa6 commit c6bd237

File tree

3 files changed

+86
-0
lines changed

3 files changed

+86
-0
lines changed

24-swap-nodes-in-pairs/cpp/main.cpp

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
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+
};

24-swap-nodes-in-pairs/go/main.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
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+
}
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
}

0 commit comments

Comments
 (0)