1. 程式人生 > >劍指offer66題--Java實現,c++實現和python實現 15.反轉連結串列

劍指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