遞歸輸出單鏈表,C#小程序

單鏈表節(jié)點:

namespace linkedlistrec.Link{
    public class Node<T> {
        public T data;
        public Node<T> next;

        public Node(T data, Node<T> next = null){
            this.data = data;
            this.next = next;
        }
    }
}

單鏈表類:

using System;

namespace linkedlistrec.Link {
    public class LinkedList {
        public Node<int> head;

        public LinkedList(int n){
            head = null;
            if(n>0){
                int i = 1;
                Node<int> rear,temp;
                head = new Node<int>(i++);
                rear = head;

                while(i<=n){
                    temp = new Node<int>(i++);
                    rear.next = temp;
                    rear = temp;
                }
            }
        }

        public bool isEmpty() {
            return head == null;
        }

        public bool isFull() {
            return false;
        }


        public int Length() {
            int i = 0;
            Node<int> temp = head;
            while(temp != null){
                i++;
                temp = temp.next;
            }
            return i;
        }

        public Node<int> index(int i) {
            if(i<=0) {
                return null;
            }

            int j = 0;
            Node<int>  temp = head;
            while(temp!=null && j<i) {
                j++;
                temp = temp.next;
            }

            return temp;
        }

        public int get(int i) {
            Node<int> temp = index(i);
            if(temp!=null){
                return temp.data;
            }else {
                return -32768;
            }
        }

        public bool set(int i, int k){
            Node<int> temp = index(i);
            if(temp!=null){
                temp.data = k;
                return true;
            }

            return false;
        }


        public void output(Node<int> p) {
            
            while(p!=null){
                Console.Write(p.data+" ");
                p = p.next;
            }

            Console.WriteLine();
        }


        public void output(){
            outputrec(head);
        }


        public void outputrec(Node<int> p) {
            if(p!=null){
                Console.Write(p.data+ " ");
                outputrec(p.next);
            }else{
                Console.WriteLine();
            }
            
        }

    }
}

主程序:

using System;
using linkedlistrec.Link;

namespace linkedlistrec
{
    class Program
    {
        static void Main(string[] args)
        {
           LinkedList lList = new LinkedList(9);
           lList.output();
        }
    }
}

程序輸出:


1.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容