2019-03-30

第十四题:输入一个链表,反转链表后,输出新链表的表头。

思路:首先定义一个新的头结点nHead为None,先用一个中间变量把当前pHead的next结点存储起来,然后让pHead结点的next更新为当前的nHead,然后将nHead更新为当前的pHead,pHead再通过中间变量更新为其原先输入链表中的next结点,重复上述操作一直到初始链表末尾为止。

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 == None or pHead.next == None:
            return pHead
        else:
            nHead = None
            while pHead != None:
                #中间变量存储pHead的next结点
                tmp = pHead.next
                #pHead.next更新为当前的nHead结点
                pHead.next = nHead
                #nHead结点更新为当前的pHead结点
                nHead = pHead
                #pHead结点更新为其在输入链表中的next结点
                pHead = tmp
            return nHead

Java

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

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        else{
            ListNode nHead = null;
            while(head != null){
                ListNode tmp = head.next;
                head.next = nHead;
                nHead = head;
                head = tmp;
            }
            return nHead;
        }
    }
}

你可能感兴趣的:(2019-03-30)