题目描述

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

 

示例1

输入

{1,2,3}

返回值

{3,2,1}

 

public class ReserverAlgo {
    public static void main(String[] args) {
        ListNode a = new ListNode(1);
        ListNode b = new ListNode(2);
        ListNode c = new ListNode(3);
        a.next = b;
        b.next = c;

        ListNode temp = a;
        while(null != temp){
            System.out.println(temp.val);
            temp = temp.next;
        }

        System.out.println("反转。。。");
        Solution s = new Solution();
        a = s.ReverseList(a);
         temp = a;
        while(null != temp){
            System.out.println(temp.val);
            temp = temp.next;
        }
    }
}

class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}

class Solution {
    public ListNode ReverseList(ListNode head) {
        if(null == head || head.next == null){
            return head;
        }
        ListNode newHead = new ListNode(0);
        ListNode temp = head;
        while(null != temp){
             // 先记录下一个节点
            ListNode p = temp.next;

             // 将当前节点设置为头节点的下一个节点
            temp.next = newHead.next;
            newHead.next = temp;
            temp = p;
        }
        return newHead.next;
    }
}