思路:这题还是比较容易的,递归和迭代复杂度仅为O(n);
// 递归版
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *hh = NULL;
ListNode *reverseList(ListNode *head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
fun(head, head->next);
return hh;
}
void fun(ListNode *p, ListNode *q)
{
if (q->next == NULL)
{
q->next = p;
p->next=NULL;
hh = q;
return;
}
else
{
fun(q, q->next);
q->next = p;
p->next = NULL;
}
}
//迭代版
ListNode *reverseList(ListNode *head) {
ListNode *prev = NULL;
ListNode *curr = head;
while (curr != NULL) {
ListNode *nextTemp = curr->next;
curr->next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}