反转链表:
/**
* 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 NULL;
ListNode *p = (ListNode*)malloc(sizeof(ListNode));
p->next = NULL;
p->val=head->val; //该处曾误写为ListNode *p=head; 致使debug花了许久时间
head=head->next;
while(head!=NULL)
{
ListNode *temp=head->next; //save the next node of head
head->next=p;
p=head;
head=temp;
}
return p;
}
};