java实现一个单链表数据结构

package com.jian.utils;
/**
 * 单链表demo
 * @author weijianyi
 *2019-11-15
 */
public class TestLinked {


	//内部类,单链表节点的结构
	class Node<T>{//使用泛型,可以存放所有类型的数据
		T value;//数据
		Node<?> next = null;//指针
		public Node(T value) {//构造方法
			this.value = value;
		}
	}
	//初始化头结点
	Node<?> head = null;
	//添加链表的方法
	public <T> void addLinkedList(T value) {
		//初始化单链表
		Node<T> newNode = new Node<T>(value);
		if(head == null) {//判断头结点是否为空
			head = newNode;//如果是空的,直接作为头结点
			return;
		}
		Node<?> temp = head;
		while(temp.next != null) {
			temp = temp.next;
		}
		temp.next = newNode;
	}
	
	//打印链表的方法
	public <T> void prin() {
		Node<?> courNode = head;
		while(courNode != null) {
			System.out.print(courNode.value+"-");
			courNode = courNode.next;
		}
	}
	//返回链表的长度
	public <T> int lenth() {
		int lenth = 0;
		Node<?> temp = head;
		while(temp != null) {
			lenth++;
			temp = temp.next;
		}
		return lenth;
	}
	//删除链表上的某个节点,传一个位置index
	public <T> boolean deleteNode(int index) {
		//先判断index的范围是否符合
		if(index <1 || index >lenth()) {//超出范围,返回false
			return false;
		}
		//特殊情况,删除的正好是头结点,好办,直接将指针指向下一个节点
		if(index == 1) {
			head = head.next;
			return true;
		}
		Node<?> preNode = head;
		Node<?> cruNode = preNode.next;
		int i=1;
		while(cruNode != null) {
			if(i == index-1) {//寻找待删除节点
				preNode.next = cruNode.next;//待删除节点的前节点指向待删除节点的后节点
				return true;
			}
			//当前节点和前节点同时往后移
			preNode = preNode.next;
			cruNode = cruNode.next;
			i++;
		}
		return true;
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {

		//测试
		TestLinked t = new TestLinked();
		t.addLinkedList(54);
		t.addLinkedList(55);
		t.addLinkedList("小明");
		t.addLinkedList(45.23d);
		t.addLinkedList(false);
		t.addLinkedList("dsf");
		System.out.print("第一次打印链表:");
		t.prin();
		System.out.println("");
		System.out.println("第一次打印链表长度"+t.lenth());
		//删除链表第二个位置的节点
		System.out.println(t.deleteNode(6)?"删除节点成功":"删除节点失败");
		System.out.print("第二次打印链表:");
		t.prin();
		System.out.println("");
		System.out.println("第二次打印链表的长度"+t.lenth());
	}

}

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

想落天外X

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值