数据结构之链表(一)

单链表的实现以及技巧:


①.节点:

关于链表中节点的创建:

public class Node {
    int val;
    //后继节点
    Node next;

    public Node(int val,Node next){
        this.val = val;
        this.next = next;
    }

    public Node(){
    }
}

②.添加节点:

//创建头结点,此头结点没有下一个节点
Node head = new Node(0,null);
//创捷第一个节点和第二个节点
Node node1 = new Node(1,null);
Node node2 = new Node(2,null);
//将3个节点连接起来
head.next = node1;
node1.next = node2;

③.对节点的遍历:

//连起来
/创建头节点
Node head = new Node(1,null);
//创建哑节点
Node dumb = new Node(-1,head);
Node node1 = new Node(2,null);
Node node2 = new Node(3,null);
Node node3 = new Node(4,null);
Node node4 = new Node(5,null);
head.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
node3.val = 100;
//遍历节点
while(head != null){
    System.out.println(head.val);
    head = head.next; 
}

④.删除链表中的节点

原理:当前节点(我们要删除的节点)的前驱的后继等于它(删除的节点)的后继

//头节点的后继节点 = 第一个节点的后继节点
head.next = head.next.next;
//当前节点的前驱节点的后继节点 = 头结点的后继节点
pre.next = head.next;

 ⑤.虚拟头节点的使用技巧

(1).哑节点也叫虚拟头结点,它本身在链表中不存在,是为了我们解决问题方便而创建的一个节点(dumb),其中dumb.next = head。

(2).使用哑节点可以对头节点和链表中的元素节点进行统一化操作,不需要单独考虑头结点的情况。

(3).注意:在我们进行返回值的时候,我们需要返回哑节点的next节点,因为我们设置的是dumb.next = head,注意不要返回错误。

⑥. LeetCode算法习题分析

19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)

给你一个链表,删除链表的倒数第 n 个结点,并且返回链表的头结点。

 

public ListNode removeNthFromEnd(ListNode head, int n) {
    //条件反射
    if(head == null) return null;
    ListNode dumb = new ListNode(-1,head);
    //定义一个快指针,用来遍历
    ListNode fast = head;
    //定义一个慢指针
    ListNode slow = dumb;
    //快指针先走
    //快指针先走n步
    for(int i = 0;i < n;i++){
        fast = fast.next;
    }
    //快指针和慢指针同时移动,当快指针到结尾时,慢指针即为倒数第n个结点
    while(fast != null){
        fast = fast.next;
        slow = slow.next;
    }
    //找到了倒数n 我们要对他进行删除
    slow.next = slow.next.next;
    return dumb.next;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值