给你一个单链表,写一段代码,翻转该链表。
代码如下:
/**
* 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* prev = NULL;
ListNode* curr = head;
ListNode* next;
while(curr)
{
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
};