Java中单链表基础

本文介绍了Java中单链表的基本概念,包括单链表的节点结构,如何建立链表,链表的遍历方法,以及如何根据节点查询内容。通过具体的代码实现和测试结果,详细阐述了单链表的操作流程。
摘要由CSDN通过智能技术生成

1.单链表的基础结构节点`

private class Node{
        Node next;
        int x;
        Node(int p) {
            this.x= p;
        }
		public Node() {
		}
    }

2.建立单链表

public Node head = new Node();
	public int size;
	 public void add(int t) {
		//建立单链表
	        Node temp = head;
	        while (temp.next != null) {
	            temp = temp.next;
	        }
	        temp.next = new Node(t);
	        size++;
	    }

3.单链表的遍历

public void printData() {
	            //把第一个节点给临时节点temp,让temp遍历
	            Node temp = head;
	            while (temp != null) {
	                temp = temp.next;
	                System.out.print(temp.p.latitude+" ");
	                if(temp.next==null)//防止空指针
	                	break;
	        }
	            System.out.println();
	    }

4.根据某个节点查询内容

public int get(int i) {
		//查询链表的第i
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java,单向链表是一种常见的数据结构,它由一系列节点组成,每个节点包含数据和指向下一个节点的指针。单向链表的特点是只能从头节点开始遍历到尾节点,不能反向遍历。 下面是一个简单的Java实现单向链表的例子: ```java public class Node { int data; // 节点数据 Node next; // 指向下一个节点的指针 public Node(int data) { this.data = data; this.next = null; } } public class LinkedList { Node head; // 链表头节点 public LinkedList() { this.head = null; } // 在链表尾部添加节点 public void add(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; } else { Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } } // 在链表查找某个节点是否存在 public boolean contains(int data) { Node current = head; while (current != null) { if (current.data == data) { return true; } current = current.next; } return false; } // 删除链表第一个出现的指定节点 public void remove(int data) { if (head == null) { return; } if (head.data == data) { head = head.next; return; } Node current = head; while (current.next != null) { if (current.next.data == data) { current.next = current.next.next; return; } current = current.next; } } // 获取链表的节点数 public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.next; } return count; } } ``` 在上面的代码Node类表示链表节点,LinkedList类表示单向链表。它包含了添加、查找、删除和获取节点数等常见操作。你可以根据自己的实际需求来对链表进行操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值