數(shù)據(jù)結構之鏈表及其棧和隊列的實現(xiàn)

鏈表的基本操作

定義

class Node{
  Item item;//表示任意的數(shù)據(jù)類型
  Node next;//指向下一個節(jié)點的引用
}

從鏈表頭部插入元素

Node oldFirst = first;//oldFirst指向原來的頭結點
first = new Node();
first.item = item;
first.next = oldFirst;

從鏈表頭部刪除元素

first = first.next; //first指向first.next即可

從鏈表尾部插入元素

Node oldLast = last;
last = new Node();
last.item = item;
oldLast.next = last;

從中間插入和刪除結點

Node first = new Node();
Node third = new Node();
first.next = third;
//在first和second之間插入second
Node second = new Node();
first.next = second;
second.next = third;
//刪除second結點(刪除結點必須知道前一個結點)
first.next = third;

棧和對列的實現(xiàn)

棧的實現(xiàn)

使用數(shù)組實現(xiàn)棧

public class ArrayStack<Item> implements Iterable<Item>{

    //初始化數(shù)組的大小
    private Item[] arr = (Item[])new Object[5];
    private int N == 0;
    
    public int size(){
        return N;
    }
    
    public boolean isEmpty(){
        return N == 0 ? true : false; 
    }
    
    public void push(Item item){
        if(N == arr.length){
            resize(2*N);
        }
        arr[N++] = item;
    }
    
    public Item pop(){
        Item item = arr[--N];
        arr[N] = null;
        if(N > 0 && N == arr.length/4){
            resize(2*N);
        }
        return item;
    }
    //動態(tài)調整數(shù)組大小
    public void resize(int capacity){
        Item[] temp = (Item[])new Object[capacity];
        for(int i = 0; i < N; i++){
           temp[i] = arr[i];
        }
        arr = temp;
    }
    
    //實現(xiàn)迭代器功能,可以使用foreach語句
    public Iterator<Item> iterator(){
        return new ArrayReverseIterator();
    }
    
    private class ArrayReverseIterator implements Iterator<Item>{
        private int index = N;
        public boolean hasNext(){
            return N > 0 ? true : false;
        }
        
        public Item next(){
            return arr[--N];
        }
    }
}

使用鏈表實現(xiàn)棧

public class NodeStack<Item> implements Iterable<Item> {

    private class Node{
        Item item;
        Node next;
    }

    private Node first;
    private int N = 0;

    public void push(Item item){
        Node oldfirst = first;
        first = new Node();
        first.item = item;
        first.next = oldfirst;
        N++;
    }

    public Item pop(){
        Item item = first.item;
        first = first.next;
        N--;
        return item;
    }

    public boolean isEmpty(){
        return N == 0;
    }

    public int size(){
        return N;
    }

    @Override
    public Iterator<Item> iterator() {
        return new ListIterator();
    }


    private class ListIterator implements Iterator<Item>{

        private Node current = first;

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }

}

隊列的實現(xiàn)

public class Queue<Item> implements Iterable<Item>{
    
    private class Node{
        Item item;
        Node next;
    }
    
    Node first;
    Node last;
    private int N = 0;
    
    public boolean isEmpty(){
        return N == 0;
    }
    
    public int size(){
        return N;
    }
    
    public void enqueue(Item item){
        Node oldLast = last;
        last = new Node();
        last.item = item;
        if(isEmpty()){
            first = last;
        }else{
            oldLast.next = last;
        }
        N++;
    }
    
    public Item dequeue(){
        Item item = first.item;
        first = first.next;
        if(isEmpty()){
            last = null;
        }
        N--;
        return item;
    }
    
    public Iterator<Item> iterator(){
       return new QueueIterator();
    }
    
    private class QueueIterator implements Iterator<Item>{
        
        private Node current = first;
        
        public boolean hasNext(){
            return current != null;
        }
        
        public Item next(){
            Item item = current.item;
            current = current.next;
            return item;
        }
        
    }
    
}

鏈表練習題目

1.有一個整數(shù)val,如何在節(jié)點值有序的環(huán)形鏈表中插入一個節(jié)點值為val的節(jié)點,并且保證這個環(huán)形單鏈表依然有序.給定鏈表的信息,及元素的值A及對應的nxt指向的元素編號同時給定val,請構造出這個環(huán)形鏈表,并插入該值。

class ListNode{
    int val;
    ListNode next;
    public ListNode(int val){
      this.val = val;
    }
}
public ListNode insert(int[] A, int[] next, int val){
    
    if(A == null || A.length == 0){
        ListNode node = new ListNode(val);
        return node;
    }
    ListNode head = new ListNode(A[0]);
    ListNode point = head;
    ListNode current = null;
    //通過數(shù)組構造鏈表
    for(int i = 0; i < next.length - 1; i++){
        current = new ListNode(A[next[i]]);
        ponit.next = current;
        point = current;
    }
    
    
    if(val < head.val){
        ListNode node = new ListNode(val);
        node.next = head;
        head = node;
        return head;
    }
    
    if(val > current.val){
       ListNode node = new ListNode(val);
       current.next = node;
       return head;
    }
    
    ListNode p1 = head;
    ListNode p2 = head.next;
    while(p1 != null && p2 != null){
        if(p1.val <= val && val <= p2.val){
            ListNode node = new ListNode(val);
            p1.next = node;
            node.next = p2;
            return head;
        }else{
            p1 = p1.next;
            p2 = p2.next;
        }
    }
    
    return head;
    
    
}

2.實現(xiàn)一個算法,刪除單向鏈表中間的某個結點,假定你只能訪問該結點。給定帶刪除的節(jié)點,請執(zhí)行刪除操作,若該節(jié)點為尾節(jié)點,返回false,否則返回true.

public boolean remove(ListNode pNode){
        if(pNode.next == null){
            return false;
        }
        pNode.val = pNode.next.val;
        pNode.next = pNode.next.next;
        return true;
}

3.對于一個鏈表,我們需要用一個特定閾值完成對它的分化,使得小于等于這個值的結點移到前面,大于該值的結點在后面,同時保證兩類結點內部的位置關系不變。給定一個鏈表的頭結點head,同時給定閾值val,請返回一個鏈表,使小于等于它的結點在前,大于等于它的在后,保證結點值不重復。

public ListNode listDivide(ListNode head,int val){

    public ListNode head_1 = null;
    public ListNode tail_1 = null;
    public ListNode head_2 = null;
    public ListNode tail_2 = null;
    public ListNode next = null;
    
    while(head != null){
       next = head.next;
       head.next = null;
       if(head.val <= val){
          ListNode oldTail_1 = tail_1;
          tail_1 = head;
          if(head_1 == null){
            head_1 = tail_1;
          }else{
            oldtail_1.next = tail_1;
          }
       }else if(head.val > val){
          ListNode oldTail_2 = tail_2;
          tail_2 = head;
          if(head_2 == null){
             head_2 = tail_2;
          }else{
             oldTail_2.next = tail_2;
          }
       }
       head = next;
    }
    
    if(tail_1 != null){
      tail_1.next = head_2;
    }
    
    return head_1 != null ? head_1 : head_2; 
    
}

4.有一個單鏈表,請設計一個算法,使得每K個節(jié)點之間逆序,如果最后不夠K個節(jié)點一組,則不調整最后幾個節(jié)點。例如鏈表1->2->3->4->5->6->7->8->null,K=3這個例子。調整后為,3->2->1->6->5->4->7->8->null。因為K==3,所以每三個節(jié)點之間逆序,但其中的7,8不調整,因為只有兩個節(jié)點不夠一組。

public ListNode inverse(ListNode head,int k){
    if(head == null || head.next == null || k < 2){
        return head;
    }
    ListNode pre = null;
    ListNode current = head;
    ListNode start = null;
    ListNode next = null;
    int count = 1;
    while(current != null){
        next = current.next;
        if(count == 3){
            start = pre == null ? head : pre.next;
            head = pre == null ? current : head;
            reverse(pre,start,current,next);
            pre = start;
            count = 0;
        }
        count++;
        current = next;
    }
    return head;
    
}

//先逆序k個節(jié)點
public void reverse(ListNode left,ListNode start,ListNode end,ListNode right){
    ListNode current = start.next;
    ListNode point = start;
    ListNode next = null;
    while(current != right){
        next = current.next;
        current.next = point;
        point = current;
        current = next;
    }
    if(left != null){
        left.next = end;
    }
    start.next = right;
}



5.如何判斷一個單鏈表是否有環(huán)?有環(huán)的話返回進入環(huán)的第一個節(jié)點的值,無環(huán)的話返回-1。

 public int chkLoop(ListNode head, int adjust) {
        if(head == null){
            return -1;
        }
        boolean isCircle = false;
        ListNode fast = head;
        ListNode slow = head;
        while(slow != null && fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                isCircle = true;
                break;
            }
        }
        if(!isCircle){
            return -1;
        }
        fast = head;
        while(slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow.val;

    }

6.現(xiàn)在有兩個無環(huán)單鏈表,若兩個鏈表的長度分別為m和n,請設計一個時間復雜度為O(n + m), 額外空間復雜度為O(1)的算法,判斷這兩個鏈表是否相交。

public boolean chkIntersect(ListNode headA, ListNode headB) {

        if(headA == null || headB == null){
            return false;
        }
        boolean isIntersect = false;
        int lenA = 0;
        ListNode p1 = headA;
        while(p1 != null){
            p1 = p1.next;
            lenA++;
        }
        int lenB = 0;
        ListNode p2 = headB;
        while(p2 != null){
            p2 = p2.next;
            lenB++;
        }
        if(lenA >= lenB){
            isIntersect = isCrossing(headA,headB,lenA - lenB);
        }else{
            isIntersect = isCrossing(headB,headA,lenB - lenA);
        }
        return isIntersect;
    }

public boolean isCrossing(ListNode headA, ListNode headB, int num){
        ListNode curA = headA;
        boolean isCross = false;
        while(num != 0){
            curA = curA.next;
            num--;
        }
        ListNode curB = headB;
        while(curA != null && curB != null){
            if(curA == curB){
                isCross = true;
                break;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return isCross;
    }

7.如何判斷兩個有環(huán)單鏈表是否相交?相交的話返回第一個相交的節(jié)點,不想交的話返回空。

public boolean chkInter(ListNode head1, ListNode head2, int adjust0, int adjust1) {

        if(head1 == null || head2 == null){
            return false;
        }

        ListNode p1 = insert(head1);
        ListNode p2 = insert(head2);
        //入環(huán)節(jié)點相交
        if(p1 == p2){
            return true;
        }
        //環(huán)中相交
        ListNode start1 = p1.next;
        while(start1 != p1){
            if(start1 == p2){
                return true;
            }
            start1 = start1.next;
        }
        return false;
    }

    //入環(huán)節(jié)點
    public ListNode insert(ListNode head){
        ListNode slow = head;
        ListNode fast = head;
        while(slow != null && fast != null){
            slow = slow.next;
            fast = fast.next.next;
            if(slow == fast){
                break;
            }
        }
        fast = head;
        while(slow != fast){
            slow = slow.next;
            fast = fast.next;
        }
        return slow;
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容