java单链表节点翻转_单链表Java实现
生活随笔
收集整理的這篇文章主要介紹了
java单链表节点翻转_单链表Java实现
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? 鏈表中的結點是以結點來表示,單鏈表每一個結點有一個指針域和data域,物理位置不是連續的,邏輯上是連續的。
代碼實現
class LinkedList<E> {private Node<E> head;private Integer size;public LinkedList(){head = new Node<>(null,null);size = 0;}//往鏈表末尾添加元素public void add(E e){Node<E> temp = head;Node<E> newNode = new Node<>(e,null);while (true){if (temp.next == null){break;}temp = temp.next;}temp.next = newNode;size++;}//指定位置插入public boolean insert(E e,int index){if (index > size || index < 0){throw new IndexOutOfBoundsException();}Node<E> temp = head;Node<E> newNode = new Node<>(e,null);for (int i = 0; i < index; i++){temp = temp.next;}if (index != size){newNode.next = temp.next;}temp.next = newNode;size++;return true;}//獲取鏈表長度public int size(){return size;}//移除元素public boolean remove(int index){if (index > size){throw new IndexOutOfBoundsException();}Node<E> temp = head;for (int i = 0; i < index; i++){temp = temp.next;}if (index == size){temp.next = null;return true;}temp.next = temp.next.next;size--;return true;}//展示所有元素public boolean show(){Node<E> temp = head;while (temp.next != null){System.out.println(temp.next.item);temp = temp.next;}return true;}public boolean isEmpty(){return size == 0;}//獲取指定索引處的元素public E get(int index){if (isEmpty()){throw new IndexOutOfBoundsException("鏈表為空");}if (index > size){throw new IndexOutOfBoundsException();}Node<E> temp = head;for (int i = 0; i < index - 1; i++){temp = temp.next;}return (E) temp.next.item;}//節點private static class Node<E>{E item;Node<E> next;Node(E element,Node<E> next){this.item = element;this.next = next;}} }簡單測試
public class LinkedListTest{public static void main(String[] args) {LinkedList<String> linkedList = new LinkedList<>();linkedList.add("你好");linkedList.add("世界");linkedList.add("哈哈");linkedList.insert("!",2);linkedList.show();System.out.println("----------------");linkedList.remove(3);linkedList.show();} }運行結果
你好 世界 ! 哈哈 ---------------- 你好 世界 !歡迎關注我的微信公眾號(禿頭之路)
總結
以上是生活随笔為你收集整理的java单链表节点翻转_单链表Java实现的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 家里wifi网速越来越慢_wifi太慢怎
- 下一篇: 德云斗笑社何九华为什么没参加_江西省会为