数据结构 单链表实现

版权声明:聂CC~ https://blog.csdn.net/ncc1995/article/details/85330828

 参考大话数据结构

  • 头插法创建链表
  • 尾插法创建链表
  • 链表任意位置插入
  • 链表任意位置删除
  • 将链表打印出来
  • 测试链表
package list;

public class SingleLinkedList {
	int size;
	Node head; //定义一个头结点表示头指针
	
	SingleLinkedList(){
		size = 0;
		head = new Node();
		//System.out.println(head.data);
	}
	
	private class Node{
		private Object data;
		private Node next;
		
		//测试构造函数
		public Node() {
			data = -1;
			next = null;
		}
		
		public Node(Object data) {
			this.data = data;
			this.next = null;
		}
	}
	
	//头插法
	public void HeadInsert(Object data) {
		//后面测试一下
		Node newNode = new Node(data);

		newNode.next = head.next;
		head.next = newNode;
		
		size++;
	}
	
	//尾插法
	public void TailInsert(Object data) {
		Node newNode = new Node(data);
		//头指针
		Node tmp = head;        /*低级错误!!!!!!!每次调用都会把head赋值给tmp*/
		
		while(tmp.next != null) {
			tmp = tmp.next;
		}
		tmp.next = newNode;
		size++;
	}
	
	//将数据插入到指定位置
	//或者利用size值
	public void Insert(int i, Object data) {
		int j;
		Node p = head;
		
		j = 1;
		
		while((p!=null) && (j<i)) {
			//当j=i-1时,p是第i-2个位置的结点
			//所以当跳出循环时,p.next指向第i个结点
			p = p.next;
			j++;
		}
		if((p==null) || (j>i) ) {
			System.out.println("插入位置不存在!!");
		}
		//创建一个新的结点
		Node s = new Node(data);
		//令新的结点指向第i个结点
		s.next = p.next;
		//将第i-1个结点指向新的结点
		p.next = s;
		
		size++;
	}
	
	//删除任意位置的结点
	public Object Delete(int i) {
		int j;
		Node p = head;
		
		j = 1;
		
		//跳出循环时,p是第i-1个位置
		while(p != null && j<i) {
			p = p.next;
			j++;
		}
		if(p == null || j >i) {
			System.out.println("删除位置不存在!!");
		}
		Object re = p.next.data;
		p.next = p.next.next;
		
		size--;
		return re;
	}
	
	public void display() {
		Node p = head;
		while(p.next != null) {
			p = p.next;
			System.out.print(p.data + " ");
		}
		System.out.println();
	}
	
	public static void main(String[] args) {
		SingleLinkedList SLList = new SingleLinkedList();
		int length = 5;
		for(int i=0; i<length; i++) {
			SLList.TailInsert(i);
		}
		SLList.display();
		
		SLList.Insert(3, "xixi");
		SLList.display();
		 
		SLList.Insert(2, "aaa");
		SLList.display();
		
		Object ele = SLList.Delete(5);
		System.out.println(ele);
		SLList.display();
		
	}
}

猜你喜欢

转载自blog.csdn.net/ncc1995/article/details/85330828
今日推荐