problems:
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
tips:
实现单链表的头尾反转.
solutions:
1.迭代法:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* newhead = NULL;
ListNode* t;
while(head)
{
t = head->next;//要修改顺序,就要存储操作位置的下一个结点
head->next = newhead;//实现反转
newhead = head;//修改当前位置
head = t;//修改操作位置
}
return newhead;
}
};
2.递归法:(暂时还未理解)参考 https://www.jianshu.com/p/125ca1a2ac22
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *newHead = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return newHead;
}
};