链表操作Java实现

单链表

存储结构

public class ListNode {
    int i;
    ListNode next;
    ListNode(int i) {
        this.i = i;
    }
    public String toString() {
        return String.valueOf(i);
    }
}

1、头插法建表

static ListNode creatFromHead() {
        ListNode head = new ListNode(-1);
        for(int i = 1; i < 5;i++) {
            ListNode p = new ListNode(i);
            p.next = head.next;
            head.next = p;
        }
        return head;
    }

2、尾插法建表

static ListNode creatFromTail() {
        ListNode head = new ListNode(-1);
        ListNode next = head;
        for(int i = 1; i < 5; i++) {
            ListNode p = new ListNode(i);
            next.next = p;
            next = p;
        }
        return head;
    }

 3、查找第i个节点

static boolean find(ListNode l, int i) {
        if(l != null) {
            System.out.println("nullpointer");
        }
        if(l.next == null || i <=0) { return false; }
        ListNode p = l.next;
        int j = 1;//统计第几个节点
        while((p.next != null) && (j<i)) {
            p = p.next;
            j++;
        }
        if(i == j) {
            return true;
        }
        return false;
    }

 4、按值查找

static boolean findValue(ListNode l, int i) {
        if(l != null) {
            System.out.println("nullpointer");
        }
        if(l.next == null) { return false; }
        ListNode p = l.next;
        while(p != null) {
            if(p.i == i) { return true; }
            p = p.next;
        }
        return false;
    }

 5、计算链表长度

static int length(ListNode l) {
        if(l != null) {
            System.out.println("nullpointer");
        }
        int count = 0;
        if(l.next == null) { return 0; }
        ListNode p = l.next;
        while(p != null) {
            count++;
            p = p.next;
        }
        return count;
    }

 6、插入元素

static boolean add(ListNode l, int i, ListNode element) {
        if(l != null && element != null) {
            System.out.println("nullpointer");
        }
        //判断输入i
        //if(i ) {}
        ListNode p = l;
        int j = 0;
        while(p.next != null && j < i-1) {
            p = p.next;
            j++;
        }
        if(j == (i-1)) {
            element.next = p.next;
            p.next = element;
            return true;
        }
        return false;
    }

 7、打印链表

static void printLinkList(ListNode head) {
        if(head != null) {
            System.out.println("nullpointer");
        }
        head = head.next;
        while(head != null) {
            ListNode next = head.next;
            System.out.print(head + " ");
            head = next;
        }
        System.out.println();
    }

 

链表的删除操作就不说了,和上面的操作差不多,先找第i-1各元素,然后改指针就OK,比较简单。

循环链表,在表的首尾进行操作比较合适。

双向链表,寻找前驱节点比较合适。

操作方式都差不多,还是要把最基本的单链表搞会,其他的变化一下就好。

 

posted @ 2019-09-27 17:57  卑微芒果  Views(442)  Comments(0Edit  收藏  举报