示例#1
0
 private SLNode Add(SLNode node, int data)
 {
     if (node == null)
     {
         return(new SLNode(data));
     }
     node.Next = Add(node.Next, data);
     return(node);
 }
示例#2
0
        static public int[] ToArray(SLNode node)
        {
            SLNode     curr = node;
            List <int> l    = new List <int>();

            while (curr != null)
            {
                l.Add(curr.Data);
                curr = curr.Next;
            }
            return(l.ToArray());
        }
示例#3
0
        /*
         * Implement an algorithm to find the nth to last element of a singly linked list.
         */
        static void Main(string[] args)
        {
            SinglyLinkedList list = new SinglyLinkedList();

            int[] numbers = { 5, 28, 15, 5, 48, 15, 7 };
            list.AddRange(numbers);
            Console.WriteLine(string.Join(" ", numbers));
            int    n       = 2;
            SLNode subList = SubListN2Last(list.GetRoot(), n);

            Console.WriteLine(string.Format("last {0} nodes: ", n) + string.Join(" ", SinglyLinkedList.ToArray(subList)));
            Console.Read();
        }
示例#4
0
        static SLNode SubListN2Last(SLNode listHead, int n)
        {
            if (listHead == null || n < 1)
            {
                return(null);
            }
            SLNode start = listHead;
            SLNode end   = listHead;

            for (int i = 0; i < n; i++)
            {
                if (end == null)
                {
                    return(null);
                }
                end = end.Next;
            }
            while (end != null)
            {
                start = start.Next;
                end   = end.Next;
            }
            return(start);
        }
示例#5
0
 public void Add(int data)
 {
     root = Add(root, data);
 }