单向链表的删除及插入操作(以头插入法建立单向链表)

注意插入和删除操作中的限制约束条件。

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 void delete(int d) throws Exception { //假设要删除的元素在该链表只出现一次。
        if(curr == null) throw new Exception("empty LinkList");
        if(curr.val == d) {curr = curr.next; return;}
        ListNode tmp = curr;
        while (tmp.next != null) {
            if(tmp.next.val == d) {tmp.next = tmp.next.next; return;}
            tmp = tmp.next;
        }
        return;
    }
    public void insert(int d) { //假设链表中的元素降序排列。
        if(curr == null) {curr = new ListNode(d); return;}
        if(d > curr.val) {
            ListNode tmp = new ListNode(d);
            tmp.next = curr;
            curr = tmp;
            return;
        }
        ListNode currTmp = curr;
        while (currTmp.next != null) {
            if(d > currTmp.next.val) {
                ListNode tmp = new ListNode(d);
                tmp.next = currTmp.next;
                currTmp.next = tmp;
                return;
            }
            currTmp = currTmp.next;
        }
        ListNode tmp = new ListNode(d);
        currTmp.next = tmp;
        return;
    }
    
    public static void main(String[] args) throws Exception {
        int[] array = new int[] {1, 2, 2, 3, 4};
        LinkList llist = new LinkList();
        for (int i = 0; i < array.length; i++) {
            llist.appendToHead(array[i]);
        }
//        llist.delete(3);
        llist.insert(0);
        llist.printAppendToHead();
    }
}

 

posted @ 2015-10-05 22:08  lasclocker  阅读(249)  评论(0编辑  收藏  举报