数据结构5——单链表习题

91 阅读1分钟

获取单链表的节点个数

public int getLength(HeroNode head){
//        空链表
        if (head.next == null){
            return 0;
        }
        int length = 0;
//        指向第一个有效节点
        HeroNode temp = head.next;
        while (temp != null){
            length ++;
            temp = temp.next;
        }
        return length;
    }

查找倒数第index个节点

思路:
1.获取链表总长度length 
2.遍历 length - index
public HeroNode findIndexNode(HeroNode head,int index){
    if (head.next == null){
        return null;
    }
    int length = getLength(head);
    if (index <= 0 || index > length){
        return null;
    }
    HeroNode temp = head.next;
    for (int i = 0; i < length - index; i++) {
        temp = temp.next;
    }
    return temp;
}

单链表反转

思路:
1.定义反转链表的头节点 
2.遍历原链表,遍历一个取出一个,让最新取出的节点指向反转链表的头节点指向的节点,反转链表的头节点指向最新取出的节点
public void reverse(HeroNode head){
        if (head.next == null || head.next.next == null){
            System.out.println("无法反转");
        }
//        反转链表的头节点
        HeroNode reHead = new HeroNode(1,"a","a");
        HeroNode temp = head.next;
        while (temp != null){
//            获取当前节点
            HeroNode a = temp;
//            节点向后移
            temp = temp.next;
//            当前取出的节点指向reHead指向的节点
            a.next = reHead.next;
//            reHead指向新加入的节点
            reHead.next = a;
        }
        head.next = reHead.next;
    }
}

有序合并两个单链表


//    把一链表加到二链表中
    public void merge(HeroNode head1,HeroNode head2){
        if (head1.next == null || head2.next == null){
            System.out.println("无法合并");
            return;
        }
//        获取第一个链表的第一个节点
        HeroNode temp1 = head1.next;
        while(temp1 != null){
            HeroNode temp2 = head2;
            boolean flag = false;
//            遍历第二个链表
            while(temp2.next != null){
                if (temp1.no == temp2.next.no){
                    System.out.println("编号重复无法合并");
                    break;
                }
                if (temp1.no < temp2.next.no){
//                    temp1.next = temp2.next;
//                    temp2.next = temp1;
//                    System.out.println("插入了");
                    flag = true;
                    break;
                }
                temp2 = temp2.next;
            }
            if (flag){
                HeroNode a = temp1;
                temp1 = temp1.next;
//                插入节点指向第一个比自己编号大的节点
                a.next = temp2.next;
                temp2.next = a;

            }else{
                HeroNode a = temp1;
                temp2.next = a;
            }
        }
        HeroNode newHead = new HeroNode(0,"","");
        newHead.next = head2.next;
        list(newHead);
    }