代码随想录Day3

移除链表元素

首先不得不说用java写链表真的是比C舒服多了。
今天的题目看一下大一时候总结的链表基本操作其实都可以搞定,最重要的是要注意细节

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        while (head != null && head.val == val) { //首先将链表开头等于val的节点移除
            head = head.next;
        }
        ListNode cur = head; 
        while (cur != null) { 
        	//经过上面的循环之后,这里cur的第一个节点肯定不等于 val
            while (cur.next != null && cur.next.val == val) {
            	//循环删除
                cur.next = cur.next.next;
            }
            cur = cur.next;
        }
        return head;
    }
}

设计链表

就是考察基本操作,不过细节要到位,不然总是出错

class MyLinkedList {

 

   class LinkedNode {
        int val;
        LinkedNode next;
        public LinkedNode() {

        }
        public LinkedNode(int val) {
            this.val = val;
        }
    }
     int size;

    LinkedNode head;

    public MyLinkedList() {
        size = 0;
        head = new LinkedNode(0);
    }


    public int get(int index) {

        if (index < 0 || index >= size) {
            return -1;
        }
        LinkedNode tmp = head;

        for (int i = 0; i <= index; i++) {
            tmp = tmp.next;
        }
        return tmp.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++;

        LinkedNode tmp = head;
        for (int i = 0; i < index; i++) {
            tmp = tmp.next;
        }
        LinkedNode toAdd = new LinkedNode(val);
        toAdd.next = tmp.next;
        tmp.next = toAdd;
    }


    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size) {
            return;
        }
        size--;
        if (index == 0) {
            head = head.next;
	    return;
        }
        LinkedNode tmp = head;
        for (int i = 0; i < index ; i++) {
            tmp = tmp.next;
        }
        tmp.next = tmp.next.next;
    }
}

反转链表

在大一的时候整理过的链表基本操作中就有,不过当时学的和这题略有出入,不过稍作改动就可以了。大一时的博客

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        while (head != null) {
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值