---
title: "双向LinkedList链表笔记"
author: "vortexchoo"
date: "2015-08-25T10:34:51Z"
tags: []
categories: ["编程语言"]
slug: "linkedlist"
draft: false
lastmod: "2015-08-25T10:42:14Z"
id: 2237807
url: "https://vortexchoo.iteye.com/blog/2237807"
---

这几天工作量不大，写了一个双向链表的实现。

在linkedlist中，每一个元素所存放的位置都可以理解成一个特殊结构的节点，这个节点分为三个部分：1.前一个节点是谁，自己，后一个节点是谁.

直接上干货

 

```
package myLinkedList;

public class MyLinkedList {
	
	private Node firstNode;
	
	private Node lastNode;
	
	private int size;
	
	/**
	 * @Chunf
	 * add an element with index
	 * @param obj
	 */
	public void add(Object obj){
		Node n = new Node();
		if(firstNode==null){
			n.setPrevious(null);
			n.setObj(obj);
			n.setNext(null);
			firstNode = n;
			lastNode = n;
		}else{
			n.setPrevious(lastNode);
			n.setNext(null);
			n.setObj(obj);
			lastNode.setNext(n);
			lastNode = n;
		}
		size++;
	}
	
	/**
	 *@author Chunf 
	 *
	 *return counts of the elements in this collection
	 */
	public int size(){
		return size;
	}
	
	/**
	 * @Chunf
	 * get an element
	 * @param obj
	 */
	public Object get(int index){
		if(firstNode==null){
			return null;
		}else{
			if(index==0){
				return firstNode.getObj();
			}else{
				Node node = firstNode;
				Object res = null;
				for(int i=1;i<=index;i++){
					res = node.getNext().getObj();
					node = node.getNext();
				}
				return res;
			}
		}
	}
	
	
	public void remove(int index){
		Node node = null;
		if(index==0){
			node = firstNode;
		}else{
			Node temp = firstNode;
			Node res = null;
			for(int i=1;i<=index;i++){
				res = temp.getNext();
				temp = temp.getNext();
			}
			node = res;
		}
		Node previousNode = node.getPrevious();
		Node nextNode = node.getNext();
		previousNode.setNext(nextNode);
		nextNode.setPrevious(previousNode);
		size--;
	}
	
	
	
	/**
	 * 
	 * @author Chunf
	 *
	 * @Time 2015年8月25日
	 */
	class Node{
		private Node previous;
		
		private Object obj;
		
		private Node next;

		public Node getPrevious() {
			return previous;
		}

		public Object getObj() {
			return obj;
		}

		public void setObj(Object obj) {
			this.obj = obj;
		}

		public Node getNext() {
			return next;
		}

		public void setNext(Node next) {
			this.next = next;
		}

		public void setPrevious(Node previous) {
			this.previous = previous;
		}

	}
}
```