AcWing 35. 反转链表
原题链接
简单
作者:
少年纵马当长歌
,
2021-03-18 12:29:11
,
所有人可见
,
阅读 323
/**
* 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) {
//迭代
/*if(head==NULL)return NULL;
ListNode* first=NULL;
ListNode* second=head;
while(second!=NULL){
ListNode* tmp=second->next;
second->next=first;
first=second;
second=tmp;
}
return first;*/
//递归
if(head==NULL||head->next==NULL)return head;
ListNode* p=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return p;
}
};