单链表的几项基本操作

112 阅读1分钟

单链表查找倒数第K个结点

public Node findKNode(Node head,int k){

Node first = head;
Node after;
int index = k;
while (index != 0){
    first = first.next;
    index--;
}

after = head;
while (first.next != null){
    first = first.next;
    after = after.next;
}

return after;

}

单链表寻找中间结点

public Node findMiddleNode(Node head){

Node first = head;
Node current = head;

while (first != null  && first.next !=null){
    first = first.next.next;
    current = current.next;
}
return current;

}

合并两个有序的单链表,合并之后的链表依然有序

思路:

  • 判断两个链表存在空链表的处理情况
  • 首先比较当前两个链表的首结点,确认以哪个作为头结点去处理
  • 头结点保持不动,设置一个临时结点,使用尾插法循环遍历两个链表的比较小的值插入到链表的后面
  • 判断最后哪个链表不为空,直接将其插入链表的尾部
public Node mergeLinkList(Node first,Node second){
    if(first == null && second == null){
        return null;
    }

    if(second == null){
        return first;
    }

    if(first == null){
        return second;
    }

    Node head;
    Node current;
    if(first.data < second.data){
        head = first;
        current = head;
        first = first.next;
    }else {
        head = second;
        current = head;
        second = second.next;
    }

    while (first !=null && second != null){
        if(first.data < second.data){
            current.next = first;
            first = first.next;
            current = current.next;
        }else {
            current.next = second;
            second = second.next;
            current = current.next;
        }
    }

    if(first != null){
        current.next = first;
    }

    if(second != null){
        current.next = second;
    }

    return head;
}

单链表的反转

思路:

  • 判断当前的链表是不是空结点或者只有一个结点
  • 使用头插法逆向添加当前的结点
public Node reveseLinklist(Node node){

    if(node == null || node.next == null){
        return node;
    }

    Node current = node;
    Node next = null;
    Node reverseNode = null;
    
    while (current != null){
        next = current.next;
        current.next = reverseNode;
        reverseNode = current;
        current = next;
    }

    return reverseNode;
}

判断当前的链表里面是否有环

判断给定的链表中是否有环。如果有环则返回true,否则返回false。

思路:双指针法

public class Solution {
    public boolean hasCycle(ListNode head) {
        if(head==null)
            return false;
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow)
                return true;
        }
        return false;
    }
}