反转链表——java

给定一个链表,请你将链表反转过来。

举例:原链表:1→2→3→4→5→null

         反转链表:5→4→3→2→1→null

代码:

package algorithm_niuke;

public class Main {
    public static Node reverseList(Node head) {
        if(head == null) {
            return head;
        }
        
        Node pre = null;
        Node next = null;
        
        while(head!=null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        
        return pre;
    }

    
    private static class Node {
        int val;
        Node next;
        
        public Node(int val) {
            this.val = val;
        }
    }
    
    public static void main(String[] args) {
        
        
    }   
}

 

posted @ 2017-09-19 16:03  傍晚的羔羊  阅读(164)  评论(0编辑  收藏  举报