Reverse a singly linked list.
Subscribe to see which companies asked this question。
代码:
/**
* 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 head;
ListNode* pre=NULL;
while( head )
{
ListNode* temp=head->next;
head->next = pre;
pre= head;
head = temp;
}
return pre;
}
};