反转单链表

如何反转单链表。

/**
 * @author miao
 *
 *         反转单链表
 */
public class ResverList {

    /**
     * @param args
     */
    public static void main(String[] args) {

        //
        ListNode head = genNode(4);
        printLink(head);
        ListNode revList = ReverseList(head);
        printLink(revList);
    }
    
    private static Random r = new Random();
    public static ListNode genNode(int m) {
        ListNode head = null;
        ListNode reHead = head;
        for(int i = 0;i<m;i++) {
            if(head == null) {
                head = new ListNode(r.nextInt(m));
                reHead = head;
            }else {
                head.next = new ListNode(r.nextInt(m));;
                head = head.next;
            }
        }
        return reHead;
    }

    public static ListNode ReverseList(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {
            next = head.next; // 当前节点的下一个节点
            head.next = pre; //
            pre = head;
            head = next;
        }
        return pre;
    }

    public static void printLink(ListNode h) {
        System.out.println("begin");
        while (h != null) {
            System.out.print(" node -> " + h.val);
            h = h.next;
        }
        System.out.println();
        System.out.println("end");
    }

}

/**
 * 单链表
 * 
 * @author miao
 *
 */
class ListNode {
    int val;
    ListNode next = null;

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

核心逻辑为

    public static ListNode ReverseList(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {
            next = head.next; // 当前节点的下一个节点
            head.next = pre; //
            pre = head;
            head = next;
        }
        return pre;
    }

 

posted @ 2020-11-15 12:01  kirkvicent  阅读(94)  评论(0编辑  收藏  举报