大家好,我是一名在算法之路上不断前进的小小程序猿!体会算法之美,领悟算法的智慧~
希望各位博友走过路过可以给我点个免费的赞,你们的支持是我不断前进的动力!!
加油吧!未来可期!!!
本次实现的是查找倒数第k个结点的按编号排序单链表。
实现代码及注释如下:
package linkedlist;/* <---这是包名
-*- coding:utf-8 -*-
作者:bob-coding
日期:2022年04月07日19:05
冲冲冲!!!*/
public class findlastindexlinkedlist {
public static void main(String[] args) {
//加入元素
Node node1 = new Node(1,"a","a");
Node node2 = new Node(4,"d","d");
Node node3 = new Node(3,"c","c");
Node node4 = new Node(2,"b","b");
//新建链表
SingleLinkedList singlelinkedlist1 = new SingleLinkedList();
//加入结点
singlelinkedlist1.add(node1);
singlelinkedlist1.add(node2);
singlelinkedlist1.add(node3);
singlelinkedlist1.add(node4);
singlelinkedlist1.showlinkedlist();
//显示第一个结点的编号
System.out.println("第一个结点的编号是" + singlelinkedlist1.showfirst());
//显示链表的长度
singlelinkedlist1.getLength();
//显示倒数第k个结点
Node res = findlastindexlinkedlist(singlelinkedlist1.getHead(),3);
System.out.printf("倒数第k元素为 "+res);
}
//遍历有效结点的个数
public static int getLength(Node head){
if(head.next == null){
return 0;
}
int length = 0;
Node cur = head.next;
while(cur != null){
length++;
cur = cur.next;
}
System.out.println(length);
return length;
}
//显示倒数第k个结点的编号
public static Node findlastindexlinkedlist(Node head,int index){
if(head.next == null){
return null;
}
Node cur = head.next;
int size = getLength(head);
if(index <= 0 || index > size){
return null;
}else{
for(int i=0;i< size - index;i++){
cur = cur.next;
}
}
return cur;
}
}
//初始化链表
class SingleLinkedList{
private Node head = new Node(0,"","");
public Node getHead() {
return head;
}
//显示链表的长度
public void getLength(){
if(head.next == null){
return;
}
int length = 0;
Node cur = head.next;
while(cur != null){
length++;
cur = cur.next;
}
System.out.println("链表的长度是"+length);
return;
}
//显示第一个结点的编号
public int showfirst(){
int a = head.next.no;
return a;
}
public SingleLinkedList() {
}
//加入结点
public void add(Node node){
Node temp = head;
boolean flag = false;
while(true){
if(temp.next == null){
break;
}
if(temp.next.no > node.no){
break;
}else if(temp.no == node.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
System.out.printf("想要插入的结点已存在~ 无法插入");
}else{
node.next = temp.next;
temp.next = node;
}
}
//打印单链表
public void showlinkedlist(){
Node temp = head.next;
if(head.next == null){
System.out.println("链表为空~");
return;
}
while (true) {
if(temp == null){
System.out.println("链表遍历完成~");
break;
}
System.out.println(temp);
temp = temp.next;
}
}
}
//初始化结点
class Node{
public int no;
public String name;
public String nickname;
public Node next;
public Node(int no, String name, String nickname) {
this.no = no;
this.name = name;
this.nickname = nickname;
}
@Override
public String toString() {
return "Node{" +
"no=" + no +
", name='" + name + '\'' +
", nickname='" + nickname + '\'' +
'}';
}
}
实现效果如图: