题目描述
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
限制:
0 <= 节点个数 <= 5000
code
- 利用数组
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode *phead = new ListNode();
ListNode *p = head;
vector<int> vals;
while(p){
vals.push_back(p->val);;
p=p->next;
}
p = phead;
for(int i=vals.size()-1; i>=0; i--){
ListNode *tmp = new ListNode();
tmp->val=vals[i];
p->next=tmp;
p=p->next;
}
p->next=NULL;
return phead->next;
}
};
- 使用三个指针:pre,cur,next
- 迭代写法
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *cur = head, *pre = NULL, *next = NULL; while(cur!=NULL){ next = cur->next;//保存next指针 cur->next = pre;//修改next指针 pre = cur;//修改pre指针 cur = next; //修改当前指针 } return pre; } };
- 递归写法
- 理解参考:如何递归反转链表
class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL){//空链表和只含一个及诶单的链表反转不变 return head; } ListNode *newHead = reverseList(head->next); head->next->next = head; head->next = NULL; return newHead; } };