单向链表的建立(头插入法)

打印链表元素的顺序与尾插入法的相反,但代码比尾插入法更简洁。

class ListNode {
    ListNode next;
    int val;
    public ListNode(int x) {
        val = x;
    }
}
public class LinkList {
    private ListNode curr = null;
    public void appendToHead(int d) {
        ListNode tail = new ListNode(d);
        tail.next = curr;
        curr = tail;
    }
    public void printAppendToHead() {
        while (curr != null) {
            System.out.println(curr.val);
            curr = curr.next;
        }
    }
    
    public static void main(String[] args) {
        LinkList llist = new LinkList();
        for (int i = 1; i < 10; i++) {
            llist.appendToHead(i);
        }
        llist.printAppendToHead();
    }
}
原文地址:https://www.cnblogs.com/lasclocker/p/4856247.html