标签:int scanner val logs put 增删改 list [] 定位
对于一个单链表来说,要求有最基本的数据节点以及一些重要的方法。
方法应该有增删改查、定位、输出、获取链表长度、排序、链表读入、链表输出。下面是我用java写的单链表
public class List { public class Node{//定义节点 public int data; public Node next; public Node(int data){ this.data = data; } } private Node head;//头节点 public Node getHead(){ return head; } public int getLength()//得到链表长度 { Node node = head; int k = 0; while(node != null){ k++; node = node.next; } return k; } public Node Locate(int index){//定位位于第index位置的节点 if(index <= 0)return null; Node node = head; int k = 1; while(node != null && k < index){ k++; node = node.next; } return node; } public void input(int n){//链表输入 if(n <= 0)return; Scanner reader = new Scanner(System.in); int value = reader.nextInt(); head = new Node(value); Node node = head; int k = 1; while(k < n){ k++; value = reader.nextInt(); node.next = new Node(value); node = node.next; } } public void print(){//链表输出 Node node = head; while(node != null){ System.out.print(node.data + " "); node = node.next; } } public void insert(int index, Node node){//链表插入 if(index <= 0 || index > getLength())return; Node cur = Locate(index); node.next = cur.next; cur.next = node; } public void delete(int index){//删除节点 if(index <= 0 || index > getLength())return; Node node = Locate(index - 1); Node del = node.next; node.next = del.next; } public void setData(int index, int data){//修改节点数据 if(index <= 0 || index > getLength())return; Node node = Locate(index); node.data = data; } public int getData(int index){//得到节点数据 if(index <= 0 || index > getLength())return -1; Node node = Locate(index); return node.data; } public void sort(){//用冒泡排序对链表进行排序 Node cur = head; Node tmp = null; while(cur != tmp){ while(cur.next != tmp){ if(cur.data > cur.next.data){ int temp = cur.data; cur.data = cur.next.data; cur.next.data = temp; } cur = cur.next; } tmp = cur; cur = head; } } }
测试代码如下:
public static void main(String[] args) { List L = new List(); System.out.println("请输入链表中的数据"); L.input(6); System.out.println("链表的长度为:" + L.getLength()); System.out.println("排序后的链表为"); L.sort(); L.print(); L.setData(4, 1000); System.out.println("把第4个数据修改为1000, 修改后如下"); L.print(); System.out.println("链表中第3个数据为: " + L.getData(3)); L.delete(2); System.out.println("删除链表中的第2个数据后,结果如下"); L.print(); }
运行结果如下:
标签:int scanner val logs put 增删改 list [] 定位
原文地址:http://www.cnblogs.com/liaoxiaolao/p/7591366.html