package dataStructure; /** * 结点类,进行结点内容的保存 * @author */ public class Node { public Object data; //存放结点 public Node next; //后继结点 public Node() { this(0, null); } public Node(Object num) { this(num, null); } public Node(Object num, Node next) { this.data = num; this.next = next; } } package dataStructure; import java.util.Scanner; public class LinkList { private Scanner input = new Scanner(System.in); public Node head; //头结点 public LinkList() { //单链表构造方法 head = new Node(); //初始化头结点 } public LinkList(int num, boolean Order) { //构造一个长度为n的单链表 this(); //初始化头结点 try { if( Order ) createOfTial( num ); else createOfHead( num );//头插法 } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void createOfHead(int num) throws Exception{ int i = 0; for(i = 0; i < num; i++){ insert(lenght(), input.next()); } } public void createOfTial(int num ) throws Exception{ int i = 0; for(i = 0; i < num; i++){ insert(lenght(), input.next()); } } public void clear(){//清空链表 head.next = null; head.data = null; } public boolean isEmpty(){ //判断带头节点的单链表是否为空 return head.next == null; } public int lenght(){//求带头结点的单链表的长度 Node p = head.next;//头指针 int lenght = 0;//计数 while(p != null){//指向后继结点 p = p.next; ++lenght; } return lenght;//返回长度 } public int get(int findNum){ //读取带头结点的单链表的第I个元素 return 0; } public void insert(int i, Object num) throws Exception {//在第i个元素前插入一个值为x的新结点 Node p = head;//初始化p为头结点,j为计数器 int j = -1; while( p != null && j < i - 1){ p = p.next; ++j; } if(j > i - 1 || p == null)//越界 throw new Exception("越界的插入,失败");//抛出异常 Node s = new Node(num);//生成新结点 s.next = p.next; p.next = s; } public void remove(int i) throws Exception{ //删除结点 Node p = head.next; int j = -1; while(p.next != null && j < i - 1){ p = p.next; j++; } if(j > i - 1 || p.next == null){ throw new Exception("删除位置不合法"); } p.next = p.next.next; } public int indexOf(Object num){ //查找值为x的结点 Node p = head.next;//初始化指针 int j = 0; while(p != null && !p.data.equals(num)){ p = p.next; j++; } if(p != null)//寻找成功,返回位置 return j; else return -1; } public void display(){//输出链表 Node node = head.next;//取有效的结点 while(node != null){ System.out.println("node.data is " + node.data); node = node.next; } System.out.println(); } } package dataStructure; import java.util.Scanner; public class TestLinkList { @SuppressWarnings("resource") public static void main(String[] args){ int n = 10; LinkList L = new LinkList();//创建链表 int i = 0; for(i = 0; i < n; i++) try { L.insert(i, i); } catch (Exception e) { e.printStackTrace(); } System.out.println("请输入i的值:"); int j = new Scanner(System.in).nextInt(); if(0 < j && j < n) System.out.println("第" + j + "个元素的前驱结点是:" + L.indexOf(j - 1)); else System.out.println("您所查找的结点不存在"); } }
java单链表基础
猜你喜欢
转载自blog.csdn.net/mathew_leung/article/details/79893286
今日推荐
周排行