---
title: "写链表有感"
author: "java2liwei"
date: "2013-07-17T22:51:46Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2013-07-29T23:37:53Z"
id: 1908936
url: "https://java2liwei.iteye.com/blog/1908936"
---

今天学习了一下链表，以前学习了数据结构，对链表就有认识，觉得链表是相当有用的，今天在蓝杰学习了感觉整个数据结构就是数据和结构，数据就不再多说，结构就是数组和链表，前几天用数组实现了队列，今天就把我实现的链表的练习发一下吧；个人感觉链表还挺有用的。

 

具体代码如下

先创建一个节点类

```
package com.lw20130717;

public class LinkNode {
	
	public  Object date;
	public  LinkNode next;

}
```

 然后是链表里的具体方法

```
package com.lw20130717;

public class LinkList {
	
	private LinkNode root ;
	private LinkNode last;
	
	
	//设置在链表中添加节点的方法
	
	public void add(Object obj){
		
		if(root==null){
			root = new LinkNode();
			root.date=obj;
			last = root;
		}else{
			LinkNode next = new LinkNode();
			next.date=obj;
			last.next=next;
			last = next;
		}
	}
	//检索出链表中的某个检索值的节点的
	
	public LinkNode getNode(int index){
		LinkNode tempLinkNode = new LinkNode();
		int num=0;
		tempLinkNode = root;
		while(num!=index){
			tempLinkNode = tempLinkNode.next; 
			num++;
		}
		return tempLinkNode;
	}
	
	//获取整个链表的长度
	public int size(){
		LinkNode tempLinkNode = new LinkNode();
		int num=0;
		tempLinkNode = root;
		while(tempLinkNode!=null){
			tempLinkNode = tempLinkNode.next;
			num++;
		}
		return num;
	}
	
	//在链表中的某个位置中插入一个节点
	
	public void insert(int index,Object obj){
		LinkNode tempLinkNode = new LinkNode();
		tempLinkNode.date=obj;
		int num = size();
		if(index==0){
			
			tempLinkNode.next=root;
			root = tempLinkNode;
			
		}else if(num==index){
			
			last.next = tempLinkNode;
			last = tempLinkNode;
			
		}else{
			
			LinkNode parent = getNode(index-1);
			LinkNode next = getNode(index);
			parent.next= tempLinkNode;
			tempLinkNode.next = next;	
		}
	}
	
	//在链表中的某个位置移除一个节点
	public void remove(int index){
		
		int num = size();
		if(index==0){
			
			root = root.next ;
			
		}else if(index==(num-1)){
			
//			LinkNode parent = getNode(index-1);
//			last = parent;
			LinkNode next =  getNode(index-1);
			next.next=null;
			
			
		}else{
			
			LinkNode parent = getNode(index-1);
			LinkNode next = getNode(index+1);
			parent.next = next;
			
		}
		if(index<0||index>(num-1)){
			
			System.out.println("索引值超出范围");
			
		}

	}

}
```

 

左后就是测试类，可以自己随便写

```
package com.lw20130717;
/**
 * 定义程序主入口类
 * @author 李伟 20130717
 *
 */

public class Manager {
	public static void main(String[]args){
		
		LinkList list = new LinkList();
		
		for(int i=0;i<10;i++){
			
			list.add("学生"+i);
			
		}
		list.insert(1, "哈哈");
		list.remove(10);
		System.out.println("总共有"+list.size());
		for(int i=0;i<10;i++){
			System.out.println(list.getNode(i).date);
		}

	}
	


}
```