本文共 2697 字,大约阅读时间需要 8 分钟。
??????????????????????????????????????????????????????????????????????????????????????
????
???????????Node?????????????????????
?????????????????????????????????????????????????????????????????????????dummy?????????
??????
??dummy????????????????????????????????????????
??????
class ListNode { public int val; public ListNode next; public ListNode(int value) { val = value; }} public class LinkedList { private ListNode dummy; public LinkedList() { dummy = new ListNode(-1); }} public void add(int location, int val) { ListNode pre = dummy; for (int i = 0; i < location; i++) { pre = pre.next; } ListNode node = new ListNode(val); node.next = pre.next; pre.next = node;} public void remove(int location) { ListNode pre = dummy; for (int i = 0; i < location; i++) { pre = pre.next; } pre.next = pre.next.next;} public int get(int location) { ListNode cur = dummy.next; for (int i = 0; i < location; i++) { cur = cur.next; } return cur.val;} public boolean contain(int val) { ListNode cur = dummy.next; while (cur != null) { if (cur.val == val) { return true; } cur = cur.next; } return false;} public void print() { ListNode cur = dummy.next; while (cur != null) { System.out.print(cur.val + "->"); cur = cur.next; } System.out.println("null");} public static void main(String[] args) { LinkedList list = new LinkedList(); list.add(0, 10); list.add(1, 20); list.add(2, 40); list.remove(1); list.print(); System.out.println(list.get(0)); System.out.println(list.get(1)); System.out.println(list.contain(50)); System.out.println(list.contain(40));} | ???? | ArrayList | LinkedList | ????? |
|---|---|---|---|
| ???add? | O(n) | O(n) | ???????????? |
| ???remove? | O(n) | O(n) | ?????? |
| ???get? | O(1) | O(n) | ArrayList???? |
| ???contain? | O(n) | O(n) | ??????? |
Solution???
LeetCode????Solution????????????????????????
??main????????????????????????????????????????????????????????????????????
转载地址:http://ahwx.baihongyu.com/