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

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

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();
    }
}

 

posted @ 2015-10-05 20:51  lasclocker  阅读(429)  评论(0编辑  收藏  举报