标签:public lse efi -- 目录 class init eth 反转链表
反转一个单链表。
输入: 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);
}
};
leetcode 206. 反转链表(Reverse Linked List)
标签:public lse efi -- 目录 class init eth 反转链表
原文地址:https://www.cnblogs.com/zhanzq/p/10569774.html