Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 700812c

Browse files
author
fupengfei
committed
12/21 COMMIT
1 parent c196e7a commit 700812c

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

‎Leetcode/24. Swap Nodes in Pairs.cpp

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/*Swap Nodes in Pairs:Given a linked list, swap every two adjacent nodes and return its head.*/
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* ListNode *next;
7+
* ListNode(int x) : val(x), next(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
ListNode* swapPairs(ListNode* head) {
13+
if(head == NULL || head->next == NULL) return head;
14+
ListNode* tmp = head->next;
15+
head->next = swapPairs(tmp->next);
16+
tmp->next = head;
17+
return tmp;
18+
}
19+
};
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*Reverse Nodes in k-Group:Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.*/
2+
/**
3+
* Definition for singly-linked list.
4+
* struct ListNode {
5+
* int val;
6+
* ListNode *next;
7+
* ListNode(int x) : val(x), next(NULL) {}
8+
* };
9+
*/
10+
class Solution {
11+
public:
12+
ListNode* reverseKGroup(ListNode* head, int k) {
13+
auto node = head;
14+
for(int i = 0; i < k; ++ i) {
15+
if(!node) return head;
16+
node = node->next;
17+
}
18+
19+
auto new_head = reverse(head, node);
20+
head->next = reverseKGroup(node, k);
21+
return new_head;
22+
}
23+
ListNode* reverse(ListNode* start, ListNode* end) {
24+
ListNode* head = end;
25+
26+
while(start != end) {
27+
auto temp = start->next;
28+
start->next = head;
29+
head = start;
30+
start = temp;
31+
}
32+
33+
return head;
34+
}
35+
};
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
/*Remove Duplicates from Sorted Array:Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length.*/
2+
class Solution {
3+
public:
4+
int removeDuplicates(vector<int>& nums) {
5+
if (nums.empty()) return 0;
6+
int j = 0, n = nums.size();
7+
for (int i = 0; i < n; ++i) {
8+
if (nums[i] != nums[j]) nums[++j] = nums[i];
9+
}
10+
return j + 1;
11+
}
12+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /