1. 程式人生 > 其它 >資料結構之雙向連結串列

資料結構之雙向連結串列

技術標籤:java資料結構與演算法java連結串列資料結構

前面已經介紹過了單鏈表,這篇文章介紹一下雙向連結串列。雙向連結串列的節點比單鏈表的節點多一個pre域,也就是存放當前節點的前一個節點地址的地方。

單鏈表裡有許多操作是要找到待操作節點的前一個節點的,而雙向連結串列則不需要,因為雙向連結串列可以得到當前節點的前一個和後一個節點資訊,可以完成相應的操作。
雙向連結串列節點:
在這裡插入圖片描述
節點類:

class Node{
	//pre表示前一個節點,next表示後一個節點
	//no表示序號,其他為一些資料
	private Node pre;
	private Node next;
	private
int no; private String name; private String nickname; public Node(int no, String name, String nickname) { this.no = no; this.name = name; this.nickname = nickname; } @Override public String toString() { return "Node{" + "no="
+ no + ", name='" + name + '\'' + ", nickname='" + nickname + '\'' + '}'; } //get set 方法省略 }

雙向連結串列類(帶頭節點):
雙向連結串列的基本操作後面追加

class TwoWayLinkedList{
	private Node head = new Node(0,"","");
	//無參建構函式
	public TwoWayLinkedList
(){ } public void setHead(Node node){ this.head = node; } public Node getHead(){ return this.head; } }

接下來就是給雙向連結串列類新增一些基本方法了,插入這裡提供按序號插入法,其他插入類似,然後就是刪除,修改,遍歷方法了。

新增節點方法(按序號插入),該方法在雙向連結串列類內部
思路:
插入節點的插入位置在cur指標的前面時
1)插入時先設定待插入節點的node的pre域,即把cur的pre域設定為node的pre域
2)再把cur的pre域對應節點的next域設為node
3)然後將cur的的pre域設為node,node的next域設為cur 即:
node.setPre(cur.getPre());
node.setNext(cur);
cur.getPre().setNext(node);
cur.setPre(node);

插入節點的插入位置在cur指標後面時又分為:在連結串列尾部插入和在連結串列頭部插入(即連結串列為空時插入第一個節點)
特別注意:插入第一個節點時和在連結串列尾部插入時,cur很容易出現空指標異常,所以要分三種插入的情況

引數:節點(Node)
返回值:無

public void add(Node node){
	//先判斷連結串列是否為空,為空說明這是插入的第一個節點
	//第一個節點插入因為head的next域為空
	//head.getNext().getPre()會報空指標異常錯誤
	//所以給第一個節點設定pre域時要直接指向head
	if(head.getNext()==null){
		node.setNext(head.getNext());
		node.setPre(head);
		head.setNext(node);
		return;
	}
	//程式碼走到這裡說明雙向連結串列至少有一個節點
	//建立一個cur指標,指向連結串列的第一個節點
	Node cur = head.getNext();
	//如果cur指向最後一個節點還沒有比待插入節點序號大的
	//就插入到連結串列最後
	while(true){
		//如果cur當前指向的節點序號大於待插入節點的序號
		//說明待插入節點應該插在cur當前指向節點的前一個位置
		//插入之後就退出迴圈,插入方法也就執行完了
		if(cur.getNo()>node.getNo()){
			node.setPre(cur.getPre());
			node.setNext(cur);
			cur.getPre().setNext(node);
			cur.setPre(node);
			break;
		}else if(cur.getNo()==node.getNo()){
			//編號存在就不插入,退出迴圈
			System.out.printf("編號%d已存在\n",node.getNo());
			break;
		}else if(cur.getNext()==null){
			//判斷當前cur指向的是不是最後一個節點
			//如果是,就插入到連結串列最後
			//進入這個if分支
			//說明待插入節點序號比前面節點序號都大
			//而且待插入節點序號不存在於連結串列中
			node.setPre(cur);
			cur.setNext(node);
			//節點初始化時,其pre與next預設指向null
			//所以不需要讓node的next域再設定為null
			//或者設為cur的next域
			break;
		}
		//如果上面的if分支一個都沒進入
		//說明cur指向的節點不滿足,讓cur指向下一個節點
		cur = cur.getNext();
	}
}

插入方法寫好之後就可以寫遍歷方法,將雙向連結串列進行列印輸出,該方法還是在雙向連結串列類內部
引數:無
返回值:無

public void print(){
	//先判斷連結串列是否為空
	if(head.getNext()==null){
		System.out.println("雙向連結串列為空");
		return;
	}
	//定義一個cur指標指向連結串列的頭節點,然後遍歷連結串列
	Node cur = head;
	//開始遍歷
	while(true){
		//cur指向連結串列最後一個節點就退出迴圈
		if(cur.getNext()==null){
			break;
		}
		//因為cur初始化是head
		//所以列印cur指向的下一個節點
		//列印時需要列印當前節點和前一個節點
		//避免插入時節點pre域出現問題
		System.out.println("now:"+cur.getNext()+
		"pre:"+cur.getNext().getPre());
		//然後讓cur指向下一個節點
		cur = cur.getNext();
	}
}

連結串列刪除思路:
1)先遍歷通過cur找到待刪除節點
此時cur指向的就是待刪除節點,讓待刪除節點的前一個節點的next域直接跨過待刪除節點指向待刪除節點的next域。
2)讓待刪除節點的下一個節點的pre域直接跨過待刪除節點指向待刪除節點的pre域

cur.getPre().setNext(cur.getNext());
cur.getNext().setPre(cur.getPre());
特別注意:如果待刪除節點是連結串列最後一個,那麼cur.getNext()就為空,2)的操作就會出現空指標異常,這裡需要判斷一下

引數:待刪除節點的序號(int)
返回值:無
該方法仍然在雙向連結串列內部

public void remove(int no){
	//先判斷連結串列是否為空
	if(head.getNext()==null){
		System.out.println("連結串列為空");
		return;
	}
	//建立一個cur指標來遍歷連結串列,初始化指向連結串列第一個節點
	Node cur = head.getNext();
	while(true){
		if(cur.getNo()==no){//找到待刪除節點
			cur.getPre().setNext(cur.getNext());
			if(cur.getNext()!=null){
				//如果待刪除節點為連結串列最後一個節點
				//不執行下面語句
				cur.getNext().setPre(cur.getPre());
			}
			break;
		}else if(cur.getNext()==null){
			//當前cur指向的是連結串列最後一個節點
			//說明沒有傳來的序號匹配不到待刪除節點
			System.out.println("沒有該編號:"+no+"節點");
			break;
		}
		//未執行上面程式碼,讓cur後移
		cur = cur.getNext();
	}
}

連結串列修改節點資訊思路:

修改節點資訊與刪除節點類似,遍歷找到待更新節點,然後替換資訊,未找到就在控制檯輸出提醒,不可修改節點序號

引數:一個節點(node)
返回值:無

public void update(Node node){
	//先判斷連結串列是否為空
	if(head.getNext()==null){
		System.out.println("連結串列為空");
		return;
	}
	//建立一個cur指標來遍歷連結串列,初始化指向連結串列第一個節點
	Node cur = head.getNext();
	while(true){
		if(cur.getNo()==node.getNo()){//找到待修改節點
			//修改節點資訊
			cur.setName(node.getName());
			cur.setNickname(node.getNickname());
			break;
		}else if(cur.getNext()==null){
			//當前cur指向的是連結串列最後一個節點
			//說明傳來節點的序號匹配不到
			System.out.println("沒有該編號:"
			+node.getNo()+"節點");
			break;
		}
		//未執行上面程式碼,讓cur後移
		cur = cur.getNext();
	}
}

之前單鏈表的操作,如:單鏈表長度,獲取倒數第k個節點,單鏈表反轉,單鏈表反向輸出,合併兩個有序單鏈表為一個單鏈表且仍然有序。
雙向連結串列的操作,下面直接給出程式碼,思路是和單鏈表的類似,就是設定節點pre域麻煩一點。

雙向連結串列全部程式碼如下:

package com.sixteen.linkedlist;

public class TwoWayLinkedListDemo {
    public static void main(String[] args) {
        TwoWayLinkedList twoWayLinkedList = new TwoWayLinkedList();
        twoWayLinkedList.add(new Node(1,"宋江","及時雨"));
        twoWayLinkedList.add(new Node(3,"吳用","智多星"));
        twoWayLinkedList.add(new Node(2,"盧俊義","玉麒麟"));
        twoWayLinkedList.add(new Node(4,"林沖","豹子頭"));
        System.out.println("原雙向連結串列-----");
        twoWayLinkedList.print();
        /*System.out.println(getSize(twoWayLinkedList.getHead()));
        twoWayLinkedList.update(new Node(2,"盧俊義222","玉麒麟222"));
        System.out.println("修改後的雙向連結串列-----");
        twoWayLinkedList.print();*/
        /*System.out.println(getTheLastIndexNode(twoWayLinkedList.getHead(), 1));
        System.out.println(getTheLastIndexNode(twoWayLinkedList.getHead(), 4));
        System.out.println(getTheLastIndexNode(twoWayLinkedList.getHead(), 2));
        System.out.println(getTheLastIndexNode(twoWayLinkedList.getHead(), 6));*/
        /*twoWayLinkedList.remove(3);
        System.out.println("-----");
        twoWayLinkedList.print();*/
        /*//reversePrint(twoWayLinkedList.getHead());
        reverse(twoWayLinkedList.getHead());
        System.out.println("反轉後的雙向連結串列-----");
        twoWayLinkedList.print();*/
        /*TwoWayLinkedList twoWayLinkedList1 = new TwoWayLinkedList();
        twoWayLinkedList1.add(new Node(1,"宋江","及時雨"));
        twoWayLinkedList1.add(new Node(3,"吳用","智多星"));
        twoWayLinkedList1.add(new Node(5,"盧俊義","玉麒麟"));
        twoWayLinkedList1.add(new Node(7,"林沖","豹子頭"));
        TwoWayLinkedList twoWayLinkedList2 = new TwoWayLinkedList();
        twoWayLinkedList2.add(new Node(2,"宋江2","及時雨2"));
        twoWayLinkedList2.add(new Node(4,"吳用4","智多星4"));
        twoWayLinkedList2.add(new Node(6,"盧俊義6","玉麒麟6"));
        twoWayLinkedList2.add(new Node(8,"林沖8","豹子頭8"));
        TwoWayLinkedList twoWayLinkedList = mergeTwoTwoWayLinkedList(twoWayLinkedList1, twoWayLinkedList2);
        twoWayLinkedList.print();*/
    }

    public static Node getTheLastIndexNode(Node head,int index){
        if (head.getNext()==null){
            return null;
        }
        int size = getSize(head);
        if (index<0 || index>size){
            return null;
        }
        Node temp = head.getNext();
        for (int i = 0; i < size-index; i++) {
            temp = temp.getNext();
        }
        return temp;
    }

    public static int getSize(Node head){
        if (head.getNext()==null){
            return 0;
        }
        int count = 0;
        Node temp = head.getNext();
        while (temp!=null){
            count++;
            temp = temp.getNext();
        }
        return count;
    }

    public static TwoWayLinkedList mergeTwoTwoWayLinkedList(TwoWayLinkedList twoWayLinkedList1,
                                                            TwoWayLinkedList twoWayLinkedList2){
        Node head1 = twoWayLinkedList1.getHead();
        Node head2 = twoWayLinkedList2.getHead();
        if (head1.getNext()==null || head2.getNext()==null){
            return head1.getNext()==null ? twoWayLinkedList2:twoWayLinkedList1;
        }
        Node cur = head1.getNext();
        Node node;
        while (cur!=null){
            node = cur;
            cur = cur.getNext();
            twoWayLinkedList2.add(node);
        }
        return twoWayLinkedList2;
    }

    public static void reverse(Node head){
        //如果連結串列為空或連結串列只有一個元素,不做任何操作
        if (head.getNext()==null){
            System.out.println("連結串列為空");
            return;
        }
        if (head.getNext().getNext()==null){
            return;
        }
        Node temp = head.getNext();
        Node reverseNode = new Node(0,"","");
        Node node;
        while (temp!=null){
            node = temp;
            temp = temp.getNext();
            if (reverseNode.getNext()==null){
                node.setNext(reverseNode.getNext());
                node.setPre(reverseNode);
                reverseNode.setNext(node);
            }else {
                node.setNext(reverseNode.getNext());
                node.setPre(reverseNode);
                reverseNode.getNext().setPre(node);
                reverseNode.setNext(node);
            }
        }
        head.setNext(reverseNode.getNext());
    }

    public static void reversePrint(Node head){
        //連結串列為空或者連結串列只有一個節點時,直接輸出
        if (head.getNext()==null){
            System.out.println("連結串列為空");
            return;
        }
        if (head.getNext().getNext()==null){
            System.out.println(head.getNext());
            return;
        }
        Node temp = head.getNext();
        //while迴圈結束之後temp定位到最後一個節點,然後再反向遍歷連結串列
        while (temp.getNext()!=null){
            temp = temp.getNext();
        }
        while (temp.getPre()!=null){
            System.out.println(temp);
            temp = temp.getPre();
        }
    }
}
class TwoWayLinkedList{
    private Node head = new Node(0,"","");

    public Node getHead() {
        return head;
    }

    public void setHead(Node head) {
        this.head = head;
    }

    public void add(Node node){
        if (head.getNext()==null){
            node.setPre(head);
            node.setNext(head.getNext());
            head.setNext(node);
            return;
        }
        Node cur = head.getNext();
        while (true){
            if (cur.getNo()>node.getNo()){
                node.setPre(cur.getPre());
                node.setNext(cur);
                cur.getPre().setNext(node);
                cur.setPre(node);
                break;
            }else if (cur.getNo()==node.getNo()){
                System.out.printf("編號%d已存在\n",node.getNo());
                break;
            }else if (cur.getNext()==null){
                node.setPre(cur);
                cur.setNext(node);
                break;
            }
            cur = cur.getNext();
        }
    }

    public void remove(int no){
        if (head.getNext()==null){
            System.out.println("連結串列為空");
            return;
        }
        Node cur = head.getNext();
        while (true){
            if (cur.getNo()==no){
                cur.getPre().setNext(cur.getNext());
                if (cur.getNext()!=null){//如果當前cur指向的是連結串列最後一個節點,就不執行下面的操作
                    cur.getNext().setPre(cur.getPre());
                }
                if (cur.getNext()==null){//找到相應節點且這個節點是最後一個節點
                    cur.getPre().setNext(null);
                }else {
                    cur.getPre().setNext(cur.getNext());
                    cur.getNext().setPre(cur.getPre());
                }
                break;
            }else if (cur.getNext()==null){
                System.out.println("沒有編號"+no+"的節點");
                break;
            }
            cur = cur.getNext();
        }
    }
    public void update(Node node){
        if (head.getNext()==null){
            System.out.println("連結串列為空");
            return;
        }
        Node cur = head.getNext();
        while (true){
            if (cur.getNo()==node.getNo()){
                cur.setName(node.getName());
                cur.setNickname(node.getNickname());
                break;
            }else if (cur.getNext()==null){
                System.out.println("沒有編號"+node.getNo()+"節點");
                break;
            }
            cur = cur.getNext();
        }
    }

    public void print(){
        if (head.getNext()==null){
            System.out.println("連結串列為空");
            return;
        }
        Node cur = head;
        while (true){
            if (cur.getNext()==null){
                break;
            }
            System.out.println("now:"+cur.getNext()+
                    "pre:"+cur.getNext().getPre());
            cur = cur.getNext();
        }
    }
}

class Node{
    private Node pre;
    private Node next;
    private int no;
    private String name;
    private String nickname;
    public Node(int no, String name, String nickname) {
        this.no = no;
        this.name = name;
        this.nickname = nickname;
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                ", name='" + name + '\'' +
                ", nickname='" + nickname + '\'' +
                '}';
    }

    public Node getPre() {
        return pre;
    }

    public void setPre(Node pre) {
        this.pre = pre;
    }

    public Node getNext() {
        return next;
    }

    public void setNext(Node next) {
        this.next = next;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }
}