java给链表赋值_Java链表操作代码[通俗易懂]

java给链表赋值_Java链表操作代码[通俗易懂]/****/packagecom.cherish.SwordRefersToOffer;/***@authoracer**/publicclasstest_22链表中倒数第k个节点{/****/publictest_22链表中倒数第k个节点(){//TODO自动生成的构造函数存根}publicstaticclassListNode{privateintval;ListNode…

大家好,又见面了,我是你们的朋友全栈君。

/****/

packagecom.cherish.SwordRefersToOffer;/***@authoracer

**/

public classtest_22链表中倒数第k个节点 {/****/

publictest_22链表中倒数第k个节点() {//TODO 自动生成的构造函数存根

}public static classListNode{private intval;

ListNode next= null;

ListNode(intval){this.val =val;

next= null;

}

}/***@paramargs*/

public static voidmain(String[] args) {//TODO 自动生成的方法存根

ListNode head = new ListNode(1);//给一个链表赋值

for(int i = 2;i<10;i++) {

insertNodeFromTail(head,newListNode(i));

}

printListNode(head);

System.out.println(FindKthToTail(head,4).val);

System.out.println(listNodeLength(head));

System.out.println(deleteFromIndex(head,4));

printListNode(head);

System.out.println(listNodeLength(head));

System.out.println(FindKthToTail(head,4).val);

}//找到倒数第k个节点

public static ListNode FindKthToTail(ListNode head,intk) {if(head == null||k <= 0) {return null;

}

ListNode p1=head;

ListNode p2=head;for(int i = 1;i

p1=p1.next;

}else{return null;

}

}while(p1.next != null) {

p1=p1.next;

p2=p2.next;

}returnp2;

}//从头部插入新节点

public static voidinsertNodeFromHead(ListNode head,ListNode newNode)

{

newNode.next=head;

head=newNode;

}//从尾部插入新节点

public static voidinsertNodeFromTail(ListNode head,ListNode newNode)

{if(head == null) {

head=newNode;return;

}

ListNode temp= head;//用temp代替head去遍历找到最后一个节点,一定不要用head自己去遍历,不然就找不到链表头了

while(temp.next != null) { //下一节点不为空

temp =temp.next;

}

temp.next= newNode;//找到最后一个节点后把新节点插入进去

}//计算链表的长度

public static intlistNodeLength(ListNode head) {if(head ==null) {return 0;

}

ListNode temp=head;int length = 0;while(temp.next != null) {

length++;

temp=temp.next;

}returnlength;

}//从特定位置删除链表

public static boolean deleteFromIndex(ListNode head,intdeleteIndex)

{if(head == null || deleteIndex<1) {return false;

}if(deleteIndex == 1) {

head=head.next;return true;

}int index = 1;

ListNode temp=head;

ListNode deleteNode;while(temp.next != null && index

index++;

temp=temp.next;

}

deleteNode=temp.next;

temp.next=deleteNode.next;return true;

}//按顺序输出链表

public static voidprintListNode(ListNode head)

{

ListNode temp=head;while(temp.next != null)

{

System.out.print(temp.val);

System.out.print(“\t”);

temp=temp.next;

}

System.out.println();

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/134120.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号