求单链表中有效节点的个数
public static int getLength(HeroNode head) {
if(head.next == null) {
return 0;
}
int length = 0;
HeroNode cur = head.next;
while(cur != null) {
length++;
cur = cur.next;
}
return length;
}
查找单链表中的倒数第 k 个结点
public static HeroNode findLastIndexNode(HeroNode head, int index) {
if(head.next == null) {
return null;
}
int size = getLength(head);
if(index <=0 || index > size) {
return null;
}
HeroNode cur = head.next;
for(int i =0; i< size - index; i++) {
cur = cur.next;
}
return cur;
}
单链表的反转
![在这里插入图片描述](https://img-blog.csdnimg.cn/20210207215102590.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3RvdXRlbmc1NQ==,size_16,color_FFFFFF,t_70)
public static void reversetList(HeroNode head) {
if(head.next == null || head.next.next == null) {
return ;
}
HeroNode cur = head.next;
HeroNode next = null;
HeroNode reverseHead = new HeroNode(0, "", "");
while(cur != null) {
next = cur.next;
cur.next = reverseHead.next;
reverseHead.next = cur;
cur = next;
}
head.next = reverseHead.next;
}
从尾到头打印单链表
果
public static void reversePrint(HeroNode head) {
if(head.next == null) {
return;
}
Stack<HeroNode> stack = new Stack<HeroNode>();
HeroNode cur = head.next;
while(cur != null) {
stack.push(cur);
cur = cur.next;
}
while (stack.size() > 0) {
System.out.println(stack.pop());
}
}
合并两个有序的单链表,合并之后的链表依然有序
public static StudentNode concat(StudentNode head1,StudentNode head2){
if(head1.next==null &head2.next==null){
return null;
}else if(head1.next==null){
return head2;
}else if(head2.next==null){
return head1;
}else {
StudentNode newhead=new StudentNode(0,"");
newhead.next=head1.next;
StudentNode temp=head2.next;
StudentNode n=null;
while (true){
if(temp==null){
break;
}else {
n=temp.next;
StudentNode cur=newhead;
while (true){
if(cur.next==null){
break;
}else if(cur.next.no>temp.no){
break;
}else if(cur.next.no==temp.no){
throw new RuntimeException("编号重复");
}
cur=cur.next;
}
temp.next=cur.next;
cur.next=temp;
}
temp=n;
}
return newhead;
}
}