JZ6 从尾到头打印链表
解法一 使用栈
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
stack<int> s;
vector<int> result;
ListNode* node = head;
while(node != NULL){
s.push(node->val);
node = node ->next;
}
while(!s.empty()){
result.push_back(s.top());
s.pop();
}
return result;
}
};
解法二 递归
class Solution {
public:
void recursion(ListNode* node,vector<int>& result){
if(node != NULL){
recursion(node->next, result);
result.push_back(node->val);
}
}
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> result;
recursion(head,result);
return result;
}
};
JZ24 反转链表
解法一 使用栈,构造新链表
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
stack<ListNode*> s;
ListNode* node = pHead;
while(node != NULL){
s.push(node);
node = node ->next;
}
if(s.empty()){return NULL;}
ListNode* ans = s.top();
s.pop();
ListNode* head = ans;
while(!s.empty()){
head->next = s.top();
s.pop();
head = head ->next;
}
head->next = NULL;
return ans;
}
};
解法二 双指针
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* ans = NULL;
while(pHead != NULL){
ListNode* tmp = pHead->next;
pHead->next = ans;
ans = pHead;
pHead = tmp;
}
return ans;
}
};
解法三 递归
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL|| pHead ->next == NULL){
return pHead;
}
ListNode* ans = ReverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return ans;
}
};
参考动画演示+多种解法 206. 反转链表