链表复制

This commit is contained in:
yaha 2023-05-24 21:09:40 +08:00
commit 59586d0eb6
3 changed files with 87 additions and 3 deletions

View File

@ -7,9 +7,6 @@
namespace yaha {
class CQueue {
public:
CQueue() {
}
void append_tail(int value);
int delete_head();
@ -20,7 +17,22 @@ private:
class String {
public:
/**
* Offer 09.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/5d3i87/
* @param s
* @return
*/
std::string replace_space(std::string s);
/**
* Offer 20.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/5d6vi6/
* @param s
* @return
*/
bool is_number(std::string s);
std::string reverse_left_words(std::string s, int n);
@ -31,7 +43,16 @@ public:
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
/**
* Offer 06.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/5dt66m/
* @param head
* @return
*/
std::vector<int> reverse_print(ListNode *head);
void reverse_stack(ListNode *head, std::vector<int> &res);
void reverse(ListNode *head, std::vector<int> &res);
};
@ -74,6 +95,19 @@ public:
private:
std::stack<int> _stk;
std::stack<int> _min_stk;
void reverse_stack(ListNode *head, std::vector<int> &res);
void reverse(ListNode *head, std::vector<int> &res);
/**
* Offer 24.
*
* @url https://leetcode.cn/leetbook/read/illustration-of-algorithm/9pdjbm/
* @param head
* @return
*/
ListNode *reverse_list(ListNode *head);
ListNode* reverse_list(ListNode* cur, ListNode* pre);
};
}

View File

@ -29,4 +29,32 @@ std::vector<int> ListNode::reverse_print(ListNode *head) {
return res;
}
ListNode* ListNode::reverse_list(ListNode* cur, ListNode* pre) {
if (cur == nullptr) {
return pre;
}
ListNode* res = reverse_list(cur->next, cur);
cur->next = pre;
return res;
}
ListNode *ListNode::reverse_list(ListNode *head) {
ListNode* cur = head;
ListNode* pre = nullptr;
while (cur) {
// 链表转存
ListNode* tmp = cur->next;
// 链表断开
cur->next = pre;
// 将当前链表值赋值给最后一个
pre = cur;
cur = tmp;
}
return pre;
// return reverse_list(head, nullptr);
}
}

View File

@ -2,6 +2,9 @@
#include "jianzhi_offer.h"
/**
* Offer 06.
*/
TEST(NodeListTest, BasicAssertions) {
yaha::ListNode *node = new yaha::ListNode(1);
node->next = new yaha::ListNode(3);
@ -22,3 +25,22 @@ TEST(NodeListStackTest, BasicAssertions) {
ASSERT_EQ(3, res[1]);
ASSERT_EQ(1, res[2]);
}
/**
* Offer 24.
*/
TEST(ListReverseTest, BasicAssertions) {
yaha::ListNode *node = new yaha::ListNode(1);
node->next = new yaha::ListNode(2);
node->next->next = new yaha::ListNode(3);
node->next->next->next = new yaha::ListNode(4);
node->next->next->next->next = new yaha::ListNode(5);
auto l = node->reverse_list(node);
ASSERT_EQ(5, l->val);
ASSERT_EQ(4, l->next->val);
ASSERT_EQ(3, l->next->next->val);
ASSERT_EQ(2, l->next->next->next->val);
ASSERT_EQ(1, l->next->next->next->next->val);
}