反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
假设存在链表 1→2→3→∅,我们想要把它改成∅←1←2←3。
在遍历列表时,将当前节点的 next 指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!
/**
* 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 *pre=NULL;
ListNode *current=head;
while(current!=NULL){
ListNode *nextNode=current->next;
current->next=pre;
pre=current;
current=nextNode;
}
return pre;
}
};
时间复杂度:O(n),假设 n是列表的长度,时间复杂度是 O(n)。
空间复杂度:O(1)。