手搓链表(java)(不完整)
文章目录
- 手搓链表(java)(不完整)
- 前言
- 一、代码
- 1.MyLinkedList类:
- 2.测试类:
- 总结
前言
提示:以下是本篇文章正文内容:
一、代码
1.MyLinkedList类:
package com.itheima.demo6;import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;public class MyLinkedList<E> {private int size;//定义一个内部类,作为链表的结点//如果定义私有的,需要添加get,set方法public static class Node<E> {E data;Node<E> next;public Node(E data, Node<E> next) {this.data = data;this.next = next;}}//add方法:可以让用户添加链表的结点,//直到用户输入exit,则返回链表的头结点。public Node<E> add() {Node<E> head = null;Scanner sc = new Scanner(System.in);while (true) {System.out.println("请你输入结点的值:");String data = sc.next();if (data.equals("exit")) break;if (head == null) {head = new Node(data, null);size++;} else {//尾插法插入结点Node<E> temp = head;while (temp.next != null) temp = temp.next;//循环结束的时候,temp.next == null//意思是temp指向最后一个结点temp.next = new Node(data, null);size++;}}return head;}//reverse方法,接收head,left,right,按上面要求进行反转。public Node<E> reverse(Node<E> head, int left, int right) {//输入异常检测:if (head == null || left < 1 || left > size || right < 1|| right > size || left == right || left > right) {return head;}//1.找到左节点的起始地址//2.将[left, right]的元素存入集合,倒着遍历,插入到原来的链表当中Node<E> first = head;Node<E> mark = null;//记入左节点List<E> data = new ArrayList<>();int index = 0;//遍历链表:while (head != null) {index++;if (index == left) mark = head;if (index >= left && index <= right)data.add(head.data);//list集合的add方法if (index == right) break;head = head.next;}//倒序遍历data集合,插入到原来的链表当中for (int i = data.size() - 1; i >= 0; i--) {E e = data.get(i);mark.data = e;mark = mark.next;}return first;}//forEach方法,遍历链表。public void forEach(Node<E> head) {//如果链表为空if (head == null) {System.out.println(head);return;}while (head != null) {System.out.print(head.data + " ");head = head.next;}}}
2.测试类:
package com.itheima.demo6;public class Test {public static void main(String[] args) {//测试类://例:1 2 3 4 5,left = 2, right = 4//输出:1 4 3 2 5MyLinkedList<String> list = new MyLinkedList<>();MyLinkedList.Node<String> head = list.add();list.forEach(head);MyLinkedList.Node<String> head2 = list.reverse(head, 2, 4);System.out.println();list.forEach(head2);}
}
总结
提示:这里对文章进行总结:
可以与手写ArrayList集合做对比