1.单链表的增、删、遍历 public class Test { @org.junit.Test public void test() { //测试代码 System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000000"); LinkedList linkedList = new LinkedList(); linkedList.add(34); linkedList.add(4); linkedList.add(6); linkedList.add(68); linkedList.add(938); linkedList.showData(); System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000000"); linkedList.delete(68); linkedList.showData(); System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000000"); System.out.println(linkedList.getIndex(111)); // linkedList.showData(); System.out.println("00000000000000000000000000000000000000000000000000000000000000000000000000"); } class Node { //定义Node对象 int data; Node next = null; Node(int data) { this.data = data; } } class LinkedList { Node head = null; public void showData() { if (head == null) { System.out.println("-1"); return; } Node current = head; int count = 0; while (current != null) { System.out.println(++count + " = " + current.data); current = current.next; } } //获取长度的过程就是遍历的过程 public int getLength() { if (head == null) { // System.out.println("-1"); return 0; } Node current = head; int count = 0; while (current != null) { // System.out.println(++count + " = " + current.data); ++count; current = current.next; } return count; } public void add(int data) { Node newNode = new Node(data); if (head == null) { head = newNode; return; } Node current = head; while (current.next != null) { current = current.next; } current.next = newNode; } //删除分为根据下标删除和根据值删除,这里是做的按值删除 public void delete(int data) { if (head == null) { return; } Node current = head; if (current.data == data) { head = current.next; return; } while (current.next != null) { Node pre = current; current = current.next; if (current.data == data) { pre.next = current.next; } } } //获取某个值在链表的下标 public int getIndex(int data) { int index = -1; if (head == null) { return index; } Node current = head; while (current != null) { index++; if (current.data == data) { return index; } current = current.next; } return -1; } } }
数据结构与算法(四)链表(一)-单链表实现
猜你喜欢
转载自blog.csdn.net/u012185875/article/details/104620432
今日推荐
周排行