反转链表

来源:互联网 发布:手机淘宝店铺分类链接 编辑:程序博客网 时间:2024/06/04 18:57

输入一个链表,反转链表后,输出链表的所有元素。

思路:从头结点开始,先独立头结点,然后将下一个结点指向头结点,然后再往下重复这个过程

C++:

 ListNode* ReverseList(ListNode* pHead) {       ListNode* pre = NULL;       ListNode* now = pHead;    while (now != NULL) {        ListNode* current=now;        now=current->next;        current->next=pre;//单独断开current结点        pre=current;    }    return pre;    }

python:

def ReverseList(self, pHead):        if not pHead or not pHead.next:            return pHead        last=None        while pHead:            cur=pHead            pHead=pHead.next            cur.next=last            last=cur        return last