1. 程式人生 > >雙向鏈表實例

雙向鏈表實例

printf urn sys col pack his bsp 前驅 ret

package com.wyl.linklist;

/**
 * 雙向鏈表,實現26個字母的循環輸出
 * @author wyl
 *
 */
public class MyBinaryLink {

    private Node head; //定義雙線鏈表的頭結點
    /**
     * 定義雙向鏈表的節點類
     */
    class Node{
        private char data; //節點的值
        private Node prior; //前驅節點
        private Node next; //後繼節點
        public Node() {
        }
        
public Node(char data) { this(data, null, null); } public Node(char data, Node prior, Node next) { this.data = data; this.prior = prior; this.next = next; } public char getData() { return data; }
public void setData(char data) { this.data = data; } public Node getPrior() { return prior; } public void setPrior(Node prior) { this.prior = prior; } public Node getNext() { return next; }
public void setNext(Node next) { this.next = next; } } /** * 構造函數初始化雙向鏈表 */ public MyBinaryLink(){ head = new Node(‘A‘, null, null); Node p = head; int i=1; for(;i<26;i++){ if(p.next == null){ char data = (char) (‘A‘ + i); Node newNode = new Node(data, p, null); p.next = newNode; p = p.next; } } p.next = head; head.prior = p; } /** * 打印雙向鏈表的值 */ public void print(){ Node p = head; while(p.next != head){ System.out.print(p.data + "、"); p = p.next; } System.out.print(p.data); } /** * 從鏈表的某個位置開始打印 * @param num 表示從鏈表的第幾個位置開始打印 */ public void printFrom(int num){ int i = 1; Node p = head; Node rear = head.prior; //找到鏈表的尾節點 Node start ; if(num > 0){ for(;i<num;i++){ p = p.next; } start = p; while(p.next != start){ System.out.print(p.data); p = p.next; } System.out.print(p.data); }else{ for(;i<-num;i++){ rear = rear.prior; } start = rear; while(rear.next != start){ System.out.print(rear.data); rear = rear.next; } System.out.print(rear.data); } } public static void main(String[] args) { MyBinaryLink myBinaryLink = new MyBinaryLink(); myBinaryLink.print(); System.out.println(); myBinaryLink.printFrom(4); System.out.println(); myBinaryLink.printFrom(-2); } }

雙向鏈表實例