题意

Reverse a singly linked list.

思路

经典的基础题,但若要求算法原地工作,要一次写对并不容易。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
struct ListNode* reverseList(struct ListNode* head)
{
if(!head || !head->next) return head;
struct ListNode *p = head, *q = head->next;
p->next = NULL;
while(q)
{
struct ListNode* nxt = q->next;
q->next = p;
p = q;
if(nxt)
{
q = nxt;
}
else
{
break;
}
}
return q;
}