原题
Reverse a singly linked list.
分析
逆序一个单链表。
链表操作的题目了,这里需要三个指针,需要额外的一个指针保存当前指针的next节点,因为逆转之后,该节点就跟原链表断开了。
代码
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(NULL==head)
return head;
ListNode* pre=head;
ListNode*cur=head->next;
ListNode*next=NULL;
while(NULL != cur)
{
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
head->next=NULL;
head=pre;
return head;
}
};