package com.peihj;
import java.util.Iterator;
/**
* 1、生成头节点
* 2、判断是否为空
* 3、判断链表长度
* 4、插入数值
* 5、再指定位置插入数值
* 6、删除数值
*/
public class SingleLinklist<T> implements Iterable{
private class Node<T>{
T item;
Node next;
public Node(T item,Node next){
this.item = item;
this.next = next;
}
}
private int N;
private Node head;
public SingleLinklist(){
head = new Node(null,null);
N = 0;
}
public boolean isempty(){
return N==0;
}
public void insert(T t){
Node n = head;
if (isempty()){
n.next = new Node(t,null);
}else {
while (n.next != null){
n = n.next;
}
n.next = new Node(t,null);
}
N++;
}
public void insert(int i,T t){
Node pre = head;
for (int j = 0; j < i; j++) {
pre = pre.next;
}
pre.next = new Node(t,pre.next);
N++;
}
public void remove(int i){
Node pre = head;
for (int j = 0; j < i; j++) {
pre = pre.next;
}
pre.next = pre.next.next;
N--;
}
// 用来反转整个链表
public void reverse(){
if (isempty()){
return;
}
reverse(head.next);
}
public Node reverse(Node curr){
if (curr.next == null){
head.next = curr;
return curr;
}
// 递归结点返回当前节点curr的下一个节点,该节点就是链表反转后当前节点的上一个节点。
Node pre = reverse(curr.next);
// 让返回节点的下一个节点变成当前节点curr
pre.next = curr;
// 把当前节点的下一个节点变为null
curr.next = null;
return curr;
}
@Override
public Iterator iterator() {
return new LIterator();
}
private class LIterator implements Iterator<T>{
private Node n;
public LIterator(){
this.n = head;
}
@Override
public boolean hasNext() {
return n.next != null;
}
@Override
public T next() {
n = n.next;
return (T) n.item;
}
}
}
class testsinglelinklist{
public static void main(String[] args) {
SingleLinklist<String> singleLinklist = new SingleLinklist<>();
singleLinklist.insert("phj");
singleLinklist.insert("zyz");
singleLinklist.insert("abc");
singleLinklist.insert("aaa");
singleLinklist.insert(1,"zhangyouzhi");
singleLinklist.remove(1);
System.out.println(singleLinklist.isempty());
for (Object o : singleLinklist) {
System.out.println(o);
}
System.out.println("=========");
singleLinklist.reverse();
for (Object o : singleLinklist) {
System.out.println(o);
}
}
}
数据结构与算法---链表反转
最新推荐文章于 2024-07-29 14:22:26 发布