栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现单链表、双向链表

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现单链表、双向链表

本文实例为大家分享了java实现单链表、双向链表的相关代码,供大家参考,具体内容如下

java实现单链表:

package code;

class Node
{
 Node next;
 int data;
 public Node(int data)
 {
 this.data=data;
 }
 
}
class linkList
{
 Node first;
 //头部
 public linkList()
 {
 this.first=null;
 }
 public void addNode(Node no)
 {
 no.next=first;
 first=no;//在头部添加
 }
 public void delectNode()
 {
 Node n=first.next;
 first=null;
 first=n;//在头部删除
 }
 //删除指定位置
 public int Number()
 {
 int count=1;
 //查看有多少元素
 Node nd=first;
 while(nd.next!=null)
 {
  nd=nd.next;
  count++;
 }
 return count;
 }
 public void delectExact(int n)
 {
 //删除指定位置
 if(n>1)
 {
  int count=1;
  Node de=first;
  while(count1)//添加指定位置
 {
  int count=1;
  Node de=first;
  while(count

java实现双向链表:

public class Doublelink
{
 public static void main(String[]args)
 {
 Node2 no=new Node2(5);
 no.addLeft(new Node2(6));
 no.addRight(new Node2(7));
 
 no.addExact2(1, new Node2(8));
 no.print();
 System.out.println("--------------");
 no.print2();
 }
}
class Node2
{
 public Node2 first;
 public Node2 end;
 public Node2 left;
 public Node2 right;
 int data=0;
 public Node2(int n)
 {
 
 first=this;
 end=this;
 
 first.data=n;
 }
 //从头部添加
 public void addLeft(Node2 before)
 {
 first.left=before;
 before.right=first;
 first=before;
 }
 //从尾部添加
 public void addRight(Node2 after)
 {
 end.right=after;
 after.left=end;
 end=after;
 }
 //插入正数(第三声)的第几个
 public void addExact(int n,Node2 no)
 {
 int count=0;
 if(n==0)
 {
  addLeft(no);
 }
 else
 { 
  Node2 f=first;
  while(true)
  {
  f=f.right;
  count++;
  if(count==n)
  {
   //此处为四个指针的指向的变化
   no.left=f.left;
   f.left.right=no;
 //  first.left=no;
   no.right=f;
   f.left=no;
   break;
  }
 
  }
 }
 }
 //插入倒数的第几个
 public void addExact2(int n,Node2 no)
 {
 int count=0;
 if(n==0)
 {
  addRight(no);
 }
 else
 {
  Node2 f=end;
  while(true)
  {
  f=f.left;
  count++;
  if(count==n)
  {
   
   no.left=f;
   no.right=f.right;
   f.right.left=no;
   f.right=no;
   break;
   
  }
  }
 }
 }
 //正序遍历
 public void print()
 {
 System.out.println(first.data);
 while(first.right!=null)
 {
  System.out.println(first.right.data);
  first=first.right;
 }
// System.out.println(end.data);
 }
 //倒序遍历
 public void print2()
 {
 System.out.println(end.data);
 while(end.left!=null)
 {
  System.out.println(end.left.data);
  end=end.left;
 }
 }
 

}


以上就是本文的全部内容,希望对大家学习java程序设计有所帮助。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/150359.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号