单向链表的附加功能
反转链表
//返回反转后的头指针
public HeroNode reverList(HeroNode head) {
if(head.next == null || head.next.next == null) {
return head;
}
HeroNode pre=null;
HeroNode cur=head.next;
HeroNode temp=cur.next;
while (true) {
cur.next=pre;
if (temp.next==null) {
temp.next=cur;
break;
}
pre=cur;
cur=temp;
temp=temp.next;
}
//定义新链表的头指针
HeroNode returnHead=new HeroNode(0, "", "");
returnHead.next=temp;
return returnHead;
}
找到倒数第k个节点
//先把链表反转再找到第k个
public void findByNo(int no) {
if(head.next == null || head.next.next == null) {
return ;
}
HeroNode head=reverList(head);
HeroNode temp=head;
for (int i = 0; i < no; i++) {
temp=temp.next;
}
System.out.println("倒数第"+no+"个为"+temp.toString());
}
双向链表
功能实现
英雄类
class HeroNode2{
public int no;
public String name;
public String nickname;
public HeroNode2 next;
public HeroNode2 pre;
public HeroNode2(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
public String toString() {
return "HeroNode [no=" + no + ", name=" + name + ", nickname=" + nickname + "]";
}
}
功能实现类
和单向链表不同的代码部分
//增加对象
public void add(HeroNode2 heroNode) {
HeroNode2 temp = head;
while (true) {
if (temp.next == null) {//
break;
}
temp = temp.next;
}
temp.next = heroNode;
heroNode.pre = temp;
}
//更新对象属性
public void update(HeroNode2 newHeroNode) {
if(head.next == null) {
System.out.println("链表为空~");
return;
}
HeroNode2 temp=head;
while (true) {
if (temp.next.no==newHeroNode.no) {
newHeroNode.next=temp.next;
temp.next=newHeroNode;
break;
}else if (temp.next==null) {
System.out.println("没有找到该英雄");
break;
}else {
temp=temp.next;
}
}
}
//删除对象
public void del(int no) {
if (head.next == null) {// 空链表
System.out.println("链表为空,无法删除");
return;
}
HeroNode2 temp=head.next;
while (true) {
if (temp==null) {
System.out.println("需要找的节点不存在");
break;
}
if (temp.no==no) {
temp.pre.next=temp.next;
temp.next.pre=temp.pre;
break;
}
temp=temp.next;
}
}
环形链表解决josepfu问题
boy类
class Boy{
int no;
Boy next;
public Boy(int no) {
super();
this.no = no;
}
@Override
public String toString() {
return "Boy [no=" + no + "]";
}
}
boy管理类
添加n个boy
public Boylist(int number) {
Boy cur = null;
for (int i = 0; i < number; i++) {
Boy boy=new Boy(i+1);
if (i==0) {
first=boy;
boy.next=boy;
cur=boy;
}else {
cur.next=boy;
boy.next=first;
cur=boy;
}
}
}
展示链表
public void showList() {
Boy temp=first;
while (true) {
System.out.println(temp);
if (temp.next==first) {
break;
}
temp=temp.next;
}
}
报数出圈
public void countList(int startNo,int countNums,int nums) {
Boy temp=first;
//出圈人数,当ccc=nums-1的时候证明只剩一个了;
int ccc=0;
//用于从1数到countNums
int tempnumbers=1;
//找到startNo
while (true) {
if (temp.no==startNo) {
break;
}
temp=temp.next;
}
while (true) {
if (tempnumbers==countNums-1) {
//为了删掉出圈的同学,判断条件为报数为countNums的前一个
System.out.println("第"+(++ccc)+"个出圈的编号为"+temp.next);
temp.next=temp.next.next;
tempnumbers=0;
}
if (ccc==nums-1) {
System.out.println(temp.toString());
break;
}
tempnumbers++;
temp=temp.next;
}
}