question:
Reverse a singly linked list.
answer:
使用三个指针遍历单链表,逐个链接点进行反转。
/** * 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 *p; ListNode *q; ListNode *r; if(head==NULL||head->next==NULL){ return head; } p=head; q=p->next; head->next=NULL; while(q!=NULL){ r=q->next; q->next=p; p=q; q=r; } head=p; return head; } };