概述
package com.algorithm.collections;
public class LinkedArrayListDemo {
public static void main(String args[]){
MyLinkedList my = new MyLinkedList();
HeroNode h1 = new HeroNode(1,"A",null);
HeroNode h2 = new HeroNode(2,"B",null);
HeroNode h3= new HeroNode(3,"C",null);
HeroNode h4 = new HeroNode(4,"D",null);
my.add(h1);
my.add(h2);
my.add(h3);
my.add(h4);
my.print();
HeroNode hn = my.getKthNode(4);
if(hn !=null)
System.out.println(hn.getName()+":" + hn.getNum());
// HeroNode reverts = my.revert();
// reverts.print(reverts);
}
}
class MyLinkedList{
HeroNode head;
public MyLinkedList(){
head = new HeroNode(0,“start”, null);
}
**public void add(HeroNode node){**
HeroNode tmpHead = head;
while(tmpHead.next !=null){
tmpHead = tmpHead.next;
}
tmpHead.next =node;
}
**public void del(HeroNode node){**
HeroNode tmpHead = head;
while(tmpHead.next !=null){
if(tmpHead.next.getNum() == node.getNum()){
tmpHead.next = tmpHead.next.next;
break;
}
tmpHead = tmpHead.next;
}
}
**public HeroNode getKthNode(int k)**{
if(k<=0)
{
System.out.println("not correct index,");
return null;
}
HeroNode hn =head.next;
HeroNode hnKthBefore =null;
boolean flag = false;
int i=1;
while(hn !=null){
if(i == k){
hnKthBefore = head.next; //初始化
flag=true;
}
if(i>k){
hnKthBefore = hnKthBefore.next;
}
i=i+1;
hn = hn.next;
}
System.out.println("i="+i);
System.out.println("k="+k);
if(i<=k && flag ==false){
System.out.println("not correct index, it is bigger than the length: "+i);
}
return hnKthBefore;
}
**public HeroNode revert()**{
HeroNode revertHead = head;
HeroNode tmp1 = null;
HeroNode tmp2 = head.next;
if(head.next !=null && head.next.next ==null )
return head;
while(tmp2 !=null){
HeroNode tmp3 = tmp2.next;
tmp2.next = tmp1;
tmp1 = tmp2;
tmp2 = tmp3;
}
revertHead.next = tmp1;
return revertHead;
}
public void print(){
HeroNode hn = head;
hn.print(hn);
}
}
class HeroNode{
private int num;
private String name;
public HeroNode next;
public HeroNode(int num, String name, HeroNode next){
this.num = num;
this.name = name;
this.next = next;
}
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void print(HeroNode hn){
while(hn !=null){
System.out.print("["+hn.getNum()+"-"+hn.getName()+"] => ");
hn = hn.next;
}
}
}
最后
以上就是顺利外套为你收集整理的单向链表操作【单链表revert,求取倒数第k个node】的全部内容,希望文章能够帮你解决单向链表操作【单链表revert,求取倒数第k个node】所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复