【Question】
Reverse a singly linked list.
借助一个辅助指针来保存当前指针的后一个节点,遍历一次即可
/**
* 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 *pre,*cur,*nex;
if (head==NULL) return head;
pre=head;
cur=head->next;
while(cur)
{
nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
head->next=NULL;
head=pre;
return head;
}
};