题目描述
反转一个单链表。
样例
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
C++ 代码
/**
* 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* phead = nullptr;
while(head)
{
ListNode* tmp = head->next;
head->next = phead;
phead = head;
head = tmp;
}
return phead;
}
};