剑指offer | 反转链表 | 13


思路分析

直接使用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
原文地址:https://www.cnblogs.com/Rowry/p/14305395.html