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) {
// if(!head||!head->next)
// return head;
ListNode *p=head;
ListNode *q=NULL;
while(p)
{
ListNode *tmp=p->next;
p->next=q;
q=p;
p=tmp;
}
return q;
}
};