剑指offer66题--Java实现,c++实现和python实现 15.反转链表

题目描述

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

C++

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        ListNode* ReverseHead = NULL;
        ListNode* pNode = pHead;
        ListNode* pPre = NULL;
        while(pNode!=NULL)
        {
            ListNode* temp = pNode->next;
            if(temp==NULL)
                ReverseHead=pNode;
            pNode->next = pPre;
            pPre = pNode;
            pNode = temp;
        }
        return ReverseHead;
    }
};

Java

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if (null == head) {
            return null;
        }
        if (head.next == null) {//只有一个节点的时候,头结点就是反转节点的头结点
            return head;
        }
        ListNode reverseHead = null;//表示反转链表的头结点
        ListNode preNode = null;
        ListNode curNode = head;
        ListNode nextNode = null;
        while (curNode!= null) {
            nextNode = curNode.next;//nextNode节点为curNode的下一个节点
            if (nextNode == null) {
                reverseHead = curNode;//如果下一个节点为null,则表示当前节点为原链表的末尾节点
            }
            curNode.next = preNode;//开始反转,让当前节点指向它的之前的节点
            preNode = curNode;//让之前的节点指向当前节点
            curNode = nextNode;//当前节点指向下一个节点:while循环里的第一句就是让这下一个节点继续向下走一步
            }
        return reverseHead;
    }
}

python

# -*- 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 is None:
            return 
        re = ListNode(pHead.val)
        while pHead.next != None:
            pHead = pHead.next
            temp = ListNode(pHead.val)
            temp.next = re
            re = temp
        return re

猜你喜欢

转载自blog.csdn.net/walter7/article/details/85272148