LinkedList 专题

1. 什么是LinkedList 

LinkedList 是由ListNode 组成的逻辑上连续 物理地址不连续的数据结构 

ListNode数据结构

public class ListNode {
    public int value;
    public ListNode next;

    public ListNode(int value) {
        this.value = value;
        next = null;
    }
}

每个节点包含两个部分,一个保存数据,另外一个指向下一个节点;

本篇文章讨论的均是单项链表(Singly LinkedList)

时间复杂度分析: 

1. 增加 O(N)

2. 删除 O(N)

3. 修改 O(N)

4. 查找 O(N)

原因是LinkedList 不支持Random Access 

LinkedList 容易出错的地方

1. 永远不要失去对链表头的控制

2. 注意不要出现NullPointerException

3.当从中间断开的时候注意清除前一个的next 

基础题目有

1. Reverse LinkedList 翻转链表

[1].Iteration

Time:O(N)

Space:O(1)

public ListNode reverse(ListNode head) {
    //Corner case 
    if(head==null || head.next==null){
      return head;
    }
    ListNode prev=null;
    ListNode curr=head;
    ListNode nex=null;
    while(curr!=null){
      nex=curr.next;
      curr.next=prev;
      prev=curr;
      curr=nex;
    }
    return prev;
  }

[2].Recursion

2. 查找中点 [by one pass] 

Time:O(N)

Space:O(1)

 public ListNode middleNode(ListNode head) {
    //Corner case 
    if(head==null || head.next==null){
      return head;
    }
    //the meaning of middle node 
    //odd:the mid     even:return the previous
    //Using fast and slow pointer 
    ListNode fast=head;
    ListNode slow=head;
    while(fast.next!=null && fast.next.next!=null){
      fast=fast.next.next;
      slow=slow.next;
    }
    return slow;
  }

3. 判断有没有环 [Space O(1)],

以及返回环开始的节点(follow up)

Time:O(N)

Space:O(1)

public boolean hasCycle(ListNode head) {
    //Using fast and slow pointer 
    //Corner case 
    if(head==null || head.next==null){
      return false;
    }
    ListNode fast=head;
    ListNode slow=head;
    while(fast.next!=null && fast.next.next!=null){
      fast=fast.next.next;
      slow=slow.next;
      if(fast==slow){
        return true;
      }
    }
    return false;
  }

这些题目会在将来的文章中进行解答

中等难度:

Reverse LinkedList in K Group

add two number

猜你喜欢

转载自www.cnblogs.com/brooksli/p/10860101.html