package com.shilei.dataStructure.linked;
/**
* @author shilei
* @date 2020/4/7-23:36
*/
public class SingleLinkedNode {
private SingleLinkedNode next;
private String msg;
public SingleLinkedNode(String msg){
this.msg=msg;
}
public void add(SingleLinkedNode node){
this.next=node;
}
//几道经典算法题
/*
* 1.链表的反转
*
* */
public SingleLinkedNode reverseLinked(){
SingleLinkedNode head = this;
SingleLinkedNode result = new SingleLinkedNode("不重要的节点");
while (head != null){
SingleLinkedNode temp = head.next;
head.next=result.next;
result.next=head;
head = temp;
}
return result.next;
}
/*
* 2.删除倒数第n个元素
*
* */
public void deleteNode(int n){
SingleLinkedNode before = this;
SingleLinkedNode after = before;
for (int i = 0;i<=n;i++){
after = after.next;//after 和 before 两个指针之间相差n个节点
}
while (after != null){
before = before.next;
after = after.next;
}
before.next = before.next.next;
}
}
单链表链表 LinkedList
最新推荐文章于 2024-08-19 16:01:20 发布