力扣:反转链表
文章目录
- 思路
- 解题方法
- 复杂度
- Code
思路
双指针算法,定义pre,和cur,来遍历链表.然后进行反转
解题方法
定义一个temp记录cur->next的位置,当反转通过cur->next=pre
来完成,
所以之后pre = cur, cur=temp(向后移动),直到cur为空,即达到遍历完成的效果
复杂度
时间复杂度:
- O ( n )
空间复杂度:
- O ( n )
Code
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
ListNode temp = new ListNode(0);
while(cur != null){
temp = cur.next; // 在cur.next改变之前
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* cur = head;
ListNode* pre = NULL;
ListNode* temp = new ListNode(0);
while(cur){
temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
};