【剑指offer】反转链表 python+c++

224 阅读1分钟

【思路】

最简单的一道题目,假设链表如下:

1-》2-》3-》4

新链表头部newhead指向1,cur指向2,并断开1与2之间的连接:

1 2-》3-》4

不断将后面链表的头结点插入前面链表头节点之前即可。且没有占用额外内存。

【代码】

python:
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        if not pHead:
            return None
        cur=pHead.next
        newhead=pHead
        pHead.next=None
        while(cur):
            next_=cur.next
            cur.next=newhead
            newhead=cur
            cur=next_
        return newhead
C++:
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if(pHead==NULL){
            return NULL;
        }
        ListNode* newhead=pHead;
        ListNode* cur=pHead->next;
        newhead->next=NULL;
        ListNode* next_=NULL;
        while(cur!=NULL){
            next_=cur->next;
            cur->next=newhead;
            newhead=cur;
            cur=next_;
        }
        return newhead;
    }
};