数据结构与算法的java实现——LinkedList

import java.util.Iterator;
import java.util.NoSuchElementException;

public class MyLinkedList<T> implements Iterable<T> {
	private int theSize;
	private Node<T> first;
	private Node<T> last;
	
	public MyLinkedList() {
		clear();
	}
	
	/**
	 * 头节点的后指针指向尾节点,尾节点的前指针指向头结点,大小设为0
	 */
	public void clear() {
		first = new Node<T>(null, null, null);
		last = new Node<T>(null, first, null);
		first.next = last;
		
		theSize = 0;
	}
	
	public int size() {
		return theSize;
	}
	
	public boolean isEmpty() {
		return size() == 0;
	}
	
	public boolean add(T data) {
		insert(size(), data);
		return true;
	}
	
	public void insert(int index, T data) {
		Node<T> p = getNode(index);
		Node<T> newNode = new Node(data, p.pre, p.pre.next);
		p.pre.next = newNode;
		p.pre = newNode;
		theSize++;
	}
	
	public T get(int index) {
		return getNode(index).data;
	}
	
	/**
	 * 将某节点的值替换为新值
	 * @param index 节点下标
	 * @param newData 新值
	 * @return 旧值
	 */
	public T set(int index, T newData) {
		Node<T> p = getNode(index);
		T oldData = p.data;
		p.data = newData;
		return oldData;
	}
	
	public T remove(int index) {
		return remove(getNode(index));
	}
	
	private T remove(Node<T> p) {
		p.pre.next = p.next;
		p.next.pre = p.pre;
		theSize--;
		return p.data;
	}
	
	private Node<T> getNode(int index){
		Node<T> current;
		current = first.next;
		for(int i=0; i<index; i++) {
			current = current.next;
		}
		return current;
	}
	
	@Override
	public Iterator<T> iterator() {
		return new MyIterator();
	}
	
	private class MyIterator implements Iterator<T>{
		private Node<T> current = first.next;
		
		@Override
		public boolean hasNext() {
			return current != last;
		}

		@Override
		public T next() {
			if(!hasNext())
				throw new NoSuchElementException();
			T data = current.data;
			current = current.next;
			return data;
		}
		
		@Override
		public void remove() {
			MyLinkedList.this.remove(current.pre);
		}
	}

	private static class Node<T>{
		public T data;
		public Node<T> pre;
		public Node<T> next;
		
		public Node(T data, Node<T> pre, Node<T> next) {
			this.data = data;
			this.pre = pre;
			this.next = next;
		}
	}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值