view Main/jungle-main/data/list/List.cs @ 35:f2ea780b3e80

fix
author Kazuma Takeda
date Wed, 22 Feb 2017 16:30:19 +0900
parents 9588ad364fdd
children
line wrap: on
line source

using System.Collections;
using System.Collections.Generic;
using System;

namespace JungleDB {
	public class List<T> : IEnumerable<T> {
		private readonly Node<T> head;

	    public List() {
	        this.head = new headNode<T>();
	    }

		// T...はC#だとparamsらしい 可変引数型というみたいだ
		public List(params T[] attributes) {
			List<T> list = new List<T> ();
			foreach (T attribute_local in attributes) {
				list = list.addLast (attribute_local);
			}
		}

	    private List(Node<T> head) {
	        this.head = head;
	    }

	    public Node<T> getHead() {
	        return head;
	    }

		public List<T> add(int num, T attribute) {
	        Node<T> newHead = head.add(0, num, attribute);
	        if (newHead == null)
	            return this;
	        return new List<T>(newHead);
	    }

	    public List<T> addLast(T attribute) {
	        Node<T> newHead = head.addLast(attribute);
			return new List<T>(newHead);
	    }


	    public T index(int num) {
	        int count = 0;
	        Node<T> currentNode = head.getNext();
	        while (currentNode != null) {
				if (count == num) {
					return currentNode.getAttribute ();
				}
	            currentNode = currentNode.getNext();
	            count++;
	        }
	        return default(T);
	    }

		public IEnumerator<T> iterator() {
			Node<T> currentNode = head.getNext();
			int count = 0;
			int len = currentNode.length();
			while (len != count) {
				yield return (T)currentNode.getAttribute();
				currentNode = currentNode.getNext ();
				count++;
			}
		}

		IEnumerator IEnumerable.GetEnumerator()
		{
			return this.GetEnumerator();
		}

		public IEnumerator<T> GetEnumerator()
		{
			return iterator ();
		}
			

		public List<T> delete(int num) {
			Node<T> newNode = head.delete(0, num);
			if (newNode == null)
				return this;
			return new List<T>(newNode);
		}

		public List<T> replace(int num, T attribute) {
			Node<T> newHead = head.replaceNode(0, num, attribute);
			if (newHead == null)
				return this;
			return new List<T>(newHead);
		}

		public T tail() {
			return index(length() - 1);
		}

		// java code head.
		public T headList() {
			return index(0);
		}

		public List<T> deleteLast() {
			return delete(head.length() - 1);
		}

		public List<T> deleteHead() {
			return delete(0);
		}

		public int length() {
			return head.length();
		}

		public List<T> append(List<T> list) {
			IEnumerator<T> iterator = list.iterator();
			List<T> newList = this;
			while (iterator.MoveNext()) {
				T attribute = iterator.Current;
				newList = newList.addLast(attribute);
			}
			return newList;
		}
	}
}