目录
- 题目描述:
- 示例:
- 进阶:
- 解法:
题目描述:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
解法:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
// method 1:
ListNode* reverseList1(ListNode* head, ListNode* & tail){
if(!head){
tail = NULL;
return NULL;
}else if(!head->next){
tail = head;
return head;
}else{
ListNode* _tail = NULL;
ListNode* nxt = head->next;
head->next = NULL;
ListNode* _head = reverseList1(nxt, _tail);
_tail->next = head;
tail = head; // update the tail node
return _head;
}
}
// method 2:
ListNode* reverseList2(ListNode* head) {
if(head){
ListNode * cur = head, * nxt = head->next;
head->next = NULL;
while(nxt){
cur = nxt;
nxt = nxt->next; // head, cur-->nxt
cur->next = head; // head<--cur, nxt
head = cur;
}
}
return head;
}
ListNode* reverseList(ListNode* head) {
// ListNode* tail = NULL;
// return reverseList1(head, tail); // accepted
return reverseList2(head);
}
};
原文地址:https://www.cnblogs.com/zhanzq/p/10569774.html
时间: 2024-11-10 00:09:22