Android代码封装

反转单链表

2018-05-12  本文已影响1人  codezwc

题目:反转单链表。

public class 反转单向链表 {

    public static class Node {
        int data;
        Node next;

        public Node(int data) {
            this.data = data;
        }
    }

    public static Node reverList(Node head) {
        if (head == null) {
            return head;
        }
        Node temp = null;
        Node curr = null;
        while (head != null) {
            curr = head.next;
            head.next = temp;
            temp = head;
            head = curr;
        }
        return temp;
    }

    public static void main(String[] args) {
        Node A1 = new Node(1);
        Node A2 = new Node(2);
        Node A3 = new Node(3);
        Node A4 = new Node(4);
        Node A5 = new Node(5);
        A1.next = A2;
        A2.next = A3;
        A3.next = A4;
        A4.next = A5;
        Node head = reverList(A1);

        while (head != null) {
            System.out.println(head.data);
            head = head.next;
        }
    }
}
上一篇 下一篇

猜你喜欢

热点阅读