反转链表——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) { } }