java链表实例

本文介绍了链表的基本概念,包括单链表、双链表和循环链表,并提供了移除链表元素的三种方法。接着,详细阐述了如何设计链表,包括单链表和双链表的数据结构及操作。此外,还讨论了翻转链表的双指针法和虚拟头指针法,以及两两交换链表节点的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 链表基本图解

单链表
在这里插入图片描述
双链表
在这里插入图片描述
循环链表
在这里插入图片描述
存储方式:存储空间不连续,以指针指向存储的位置
在这里插入图片描述
链表优点:删除或者添加节点的时候只需要将指针的指向改变就行,与数组相比复杂度降低了许多。
缺点:遍历寻址浪费时间
在这里插入图片描述

2. 移除链表元素

class Solution {
    public ListNode removeElements(ListNode head, int val) {
      //1 使用虚拟头指针
        if (head == null){
            return head;
        }

        ListNode dummy = new ListNode(-1, head);        //虚拟头节点,防止头节点被删除情况下需要单独操作
        ListNode pre = dummy;
        ListNode cur = head;

        while (cur != null){
            if (cur.val == val){
                pre.next = cur.next;                    //直接将指针指向删除元素下一个就好了
            }
            else{
                pre = cur;                             //不删除的话pre指针跟着cur走就好了
            }
            cur = cur.next;
        }
        return dummy.next;
    }
}

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        //2 不添加虚拟节点,但是有pre的方式
        while (head != null && head.val == val){      //注意:需要优先处理head,不然有可能空了但是却没办法判断
            head = head.next;                         //如[7,7,7,7,7]7  先处理完成为空,直接不用执行其他的
        }

        if (head == null){
            return head;
        }

        ListNode pre = head;
        ListNode cur = head.next;

        while (cur != null){
            if (cur.val == val){
                pre.next = cur.next;                    //直接将指针指向删除元素下一个就好了
            }
            else{
                pre = cur;                             //不删除的话pre指针跟着cur走就好了
            }
            cur = cur.next;
        }
        return head;
    }
}

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        //3 不使用虚拟头指针
        while(head != null && head.val == val){
            head = head.next;                      //删除头节点的方法就是直接指向后一个就好了
        }
        if (head == null){
            return head;
        }

        ListNode cur = head;

        while (cur != null){
            while (cur.next != null && cur.next.val == val){
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }
        return head;
    }    
}

3. 设计链表

//1 针对单链表来说
class ListNode {
    int val;
    ListNode next;
    ListNode(){}

    ListNode(int val){
        this.val = val; 
    }
}


class MyLinkedList {
    int size;       //链表大小
    ListNode head;       //头节点

    public MyLinkedList() {
        size = 0;
        head = new ListNode(0);
    }
    
    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
       
        ListNode pre = head;
        for (int i = 0; i <= index; i ++) {     //需要包含,因为index和i的索引都是从0开始,一一对应的
                pre = pre.next;
        }
        return pre.val;
    }
    
    public void addAtHead(int val) {
      addAtIndex(0, val);
    }
    
    public void addAtTail(int val) {
        addAtIndex(size, val);

    }
    
    public void addAtIndex(int index, int val) {
        
        if (index > size)  return;
        if (index < 0)  index = 0;
                                                     //添加一个值后size增加一
        size ++;                                     //当找到size的时候,对应的指针指向它的前驱节点
        ListNode pred = head;
        for (int i = 0; i < index; i ++){
                pred = pred.next;                     //找到前驱节点
            }

        ListNode newNode = new ListNode(val);
        newNode.next = pred.next;
        pred.next = newNode;  
    }
    
    public void deleteAtIndex(int index) {

        if (index < 0 || index >= size) {
            return;
        }

        size --;                                  //删除一个节点后尺寸size减小一

        if (index == 0){
            head = head.next;
        return;
        }

        ListNode pred = head;

        for (int i = 0; i < index; i ++){
            pred = pred.next;               //找到前驱节点
        }
        pred.next = pred.next.next;
    }
}

//2 双链表
class ListNode {
    int val;
    ListNode next, prev;
    ListNode() {};

    ListNode(int val) {
        this.val = val;
    }
}


class MyLinkedList {
    int size;       //链表大小
    ListNode head, tail;       //头节点, 尾节点      

    public MyLinkedList() {
        this.size = 0;
        this.head = new ListNode(0);
        this.tail = new ListNode(0);
        head.next = tail;
        tail.prev = head;
    }
    
    public int get(int index) {
        if (index < 0 || index >= size) {
            return -1;
        }
       
        ListNode cur = head;
        if (index >= size / 2) {        //判断从哪一边遍历时间会短一点
            cur = tail;
            for (int i = 0; i < size - index; i ++) {
                cur = cur.prev;
            }
        }
        else{
            for (int i = 0; i <= index; i ++) {
                cur = cur.next;
            }                 
        }
        return cur.val;
    }


    public void addAtHead(int val) {
      addAtIndex(0, val);
    }
    
    public void addAtTail(int val) {
        addAtIndex(size, val);

    }
    
    public void addAtIndex(int index, int val) {
        
        if (index > size)  return;
        if (index < 0)  index = 0;
                                                     //添加一个值后size增加一
        size ++;                                     //当找到size的时候,对应的指针指向它的前驱节点
        ListNode pred = head;
        for (int i = 0; i < index; i ++){
                pred = pred.next;                     //找到前驱节点
            }

        ListNode newNode = new ListNode(val);
        newNode.next =  pred.next;                    //需要从后面开始处理,不然会报错
        pred.next.prev = newNode;
        newNode.prev = pred;
        pred.next = newNode; 
    }
    
    public void deleteAtIndex(int index) {

        if (index < 0 || index >= size) {
            return;
        }

        size --;                                  //删除一个节点后尺寸size减小一

        if (index == 0){
            head = head.next;
        return;
        }

        ListNode pred = head;

        for (int i = 0; i < index; i ++){
            pred = pred.next;               //找到前驱节点
        }
        pred.next.next.prev = pred;                //需要从后面开始处理,不然会报错
        pred.next = pred.next.next;
        
    }
}

4. 翻转链表

//1 双指针法
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode cur = head;
        ListNode temp = null;       //缓存指针

        while (cur != null) {
            temp = cur.next;        //将指针的指向交换
            cur.next = pre;
            pre = cur;
            cur = temp;
        }
    return pre;
    } 
}
//2 虚拟头指针法
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode dummy = new ListNode(-1);
        ListNode cur = head;
        ListNode temp = null;

        while (cur != null) {
            temp = cur.next;        //将指针的指向交换
            cur.next = dummy.next;
            dummy.next = cur;
            cur = temp;
        }
    return dummy.next;
    } 
}
//3 栈方法
class Solution {
    public ListNode reverseList(ListNode head) {
        if (head == null) return null;            //为空
        if (head.next == null) return head;       //只有一个元素

        Stack<ListNode> stack = new Stack<>();    //创建栈
        ListNode cur = head;

        while (cur != null){                        //元素依次入栈
            stack.push(cur);
            cur = cur.next;
        }

        //创建一个虚拟头节点
        ListNode pHead = new ListNode(0);
        cur = pHead;
        while (!stack.isEmpty()) {                      //元素怒依次出栈
            ListNode node = stack.pop();
            cur.next = node;
            cur = cur.next;
        }

        cur.next = null;                            //最后一个元素要为null
        return pHead.next;
    }
}

5. 两两交换链表中的节点

在这里插入图片描述

class Solution {
    public ListNode swapPairs(ListNode head) {
        ListNode dummy = new ListNode(-1);              //创建虚拟头节点
        dummy.next = head;
        ListNode cur = dummy;
        ListNode temp;              //保存第三个节点
        ListNode firstNode;         //缓存第一个
        ListNode secondNode;        //缓存第二个

        while (cur.next != null && cur.next.next != null) {
            temp = cur.next.next.next;
            firstNode = cur.next;
            secondNode = cur.next.next;
           
            cur.next = secondNode;                     
            secondNode.next = firstNode;
            firstNode.next = temp;
            cur = firstNode;
        }
        return dummy.next;
    }
}

//2 递归思想
class Solution {
    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null)  return head;

        ListNode next = head.next;
        ListNode swapNode = swapPairs(next.next);     //递归

        next.next = head;                          //交换操作
        head.next = swapNode;

        return next;
     }
}

6. 删除链表中倒数第N个节点

//1 先统计个数,再删除
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        
        ListNode dummy = new ListNode(-1);     //创建虚拟头节点
        dummy.next = head;
        ListNode cur = head;
        int size = 0;                  //统计链表节点个数

        while (cur != null) {
            size ++;
            cur = cur.next;
        }

        ListNode pred = dummy;         
        for (int i = 0; i < size - n; i ++) {     //寻找前驱节点
            pred = pred.next;
        }

        pred.next = pred.next.next;
        return dummy.next;
    }
}
// 2 快慢指针
class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode slowPoint = dummy;
        ListNode fastPoint = dummy;

        for (int i = 0; i < n; i ++){
            fastPoint = fastPoint.next;          //使得快慢指针相差n个
        }

        while (fastPoint.next != null) {             //快慢指针同时向后直到最后
            fastPoint = fastPoint.next;            
            slowPoint = slowPoint.next;
        }

        slowPoint.next = slowPoint.next.next;       //此时的slowPoint是前驱节点,执行删除
        return dummy.next;
    }
}

7. 链表相交

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        int lenA = 0;   //记录两个链表的长度
        int lenB = 0;
        ListNode preA = headA;
        ListNode preB = headB;

        while (preA != null) {         //获取A的长度
            lenA ++;
            preA = preA.next;
        }

        while (preB != null) {        //获取B的长度
            lenB ++;
            preB = preB.next;
        }

        ListNode curA = headA;                   //指针重新指向头节点
        ListNode curB = headB; 

        if (lenA < lenB) {                                 //让curA指向较长的链表
            int tempLen = lenA;
            lenA = lenB;
            lenB = tempLen;

            ListNode tempNode = curA;
            curA = curB;
            curB = tempNode;
        }

        int gap = lenA - lenB;
        while ( gap > 0) {                         //将curA移动到和curB的开始处对齐
            curA = curA.next; 
            gap --;
        }

        while (curA != null) { 
            if (curA == curB) {                                 //找到值相同的点
                return curA;
            }
            curA = curA.next;
            curB = curB.next;
        }
        return null;     
    }

8.环形链表

在这里插入图片描述

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;   

            if (fast == slow) {           //如果有环,快慢指针一定相遇。类似于操场跑步。跑的快的一定会追上慢的
                ListNode node1 = head;
                ListNode node2 = fast;

                while (node1 != node2) {      //都按照一步走就能找到入环处
                    node1 = node1.next;
                    node2 = node2.next;
                }
                return node1;
            } 
            
        }
        return null; 
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值