目录
思路分析
直接使用3个指针,pre
,cur
,ne
就可以解决
cpp
/**
* 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,*cur=head;
while(cur){
auto ne = cur->next;
cur->next = pre;
pre = cur,cur=ne;
}
return pre;
}
};
python
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
pre,cur=None,head
while cur:
ne = cur.next
cur.next = pre
pre=cur
cur = ne
return pre