一、思路
反转链表。
从头遍历链表,将当前节点的next指向前项节点即可,但如果没有中间变量,就无法从该节点沿着原来的链表顺序继续往后走,所以需要一个中间变量
r
r
r,让
r
r
r先指向该节点的next,然后将该节点的next指向前项节点,该节点变成前项节点,
r
r
r变成下一个当前节点。(说的有点多,过程都说出来了。。)
1.示例图
二、代码
1.python
代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reverseList(self, head) :
p = ListNode(0)
r = ListNode(0)
p = p.next
q = head
while q :
r = q.next
q .next = p
p = q
q = r
return q
2.C++
/**
* 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 * p = nullptr, *q = head, * r = new ListNode(0);
while(q){
r = q->next;
q->next = p;
p = q;
q = r;
}
return p;
}
};