《剑指offer》 反转链表

本题来自《剑指offer》 反转链表

题目:

   输入一个链表,反转链表后,输出新链表的表头。

思路:

   需要三个变量,来保存当前节点的,前面节点和反转后的节点。

C++ Code:

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if (!pHead){                        //边界处理
            return NULL;
        }
        ListNode* pNode = pHead;            //存放当前节点
        ListNode* pRe = NULL;               //存放前的节点
        ListNode* pRev = NULL;              //存放之后的节点
        while (pNode){
            ListNode* pNext = pNode->next;  //防止断裂,提前保存之后的节点
            if (!pNext){                    //判断是不是尾节点
                pRev = pNode;               //是尾节点,则此时便为头结点
            }
            pNode->next = pRe;              //挂链,指向前链
            pRe = pNode;                    //将当前节点前移
            pNode = pNext;                  //又转向下个节点
        }
        return pRev;                        //返回倒置的节点
    }
};

Python Code1:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        cur,prev = pHead,None              #直接采用值传递复制
        while cur:
            cur.next,prev,cur = prev,cur,cur.next
        return prev

Python Code2:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        cur,prev,temp = pHead,None,None        #需要中间变量进行保存当前的值
        while cur:
            temp = cur.next
            cur.next = prev
            prev = cur
            cur = temp
        return prev

Python Code3:

# -*- coding:utf-8 -*-
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
class Solution:
    # 返回ListNode
    def ReverseList(self, pHead):
        # write code here
        if pHead == None:            #首先判断该链表是否为空
            return None
        else:    #
            i = pHead
            j = pHead.next
            if j == None:            #如果传入的链表是不空的,判断链表是否只有一个元素
                return i             #如果只有一个就直接返回这一个元素即可
            i.next = None            #先将第一个元素的的子节点赋空
            while True:    
                if j.next:           #判断后节点是否为空,不为空说明没有到尾节点
                    temp = j.next    #将该节点的子节点保存起来
                    j.next = i       #续链,串联前面的节点
                    i = j            #保存该节点的地址
                    j = temp         #地址后移到下一个
                else:                #如果是最后一个节点了就直接将前面的节点串接起来即可
                    j.next = i
                    break
        return j

总结:

原文地址:https://www.cnblogs.com/missidiot/p/10783587.html