太经典了,以至于不用放题目了~直接放代码吧!
【解答】
思路是头插法,过程见图。整个过程中pre一直指向1,每次都把pre后面的结点放到最前面,使它成为head。
/**
* 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||head->next==NULL)
return head;
ListNode *pre = head;
ListNode *cur = head->next;
while(cur!=NULL){
pre->next = cur->next;
cur->next = head;
head = cur;
cur = pre->next;
}
return head;
}
};