Day3 | 203. 移除链表元素 | 707.设计链表 | 206.反转链表

79 阅读1分钟

203. 移除链表元素 - 力扣(LeetCode)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 * int val;
 * ListNode next;
 * ListNode() {}
 * ListNode(int val) { this.val = val; }
 * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;

        while (head.next != null) {
            if (head.next.val == val) {
                head.next = head.next.next;
            } else {
                head = head.next;
            }
        }

        return dummy.next;

    }
}

707. 设计链表 - 力扣(LeetCode)

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 cur = head;
        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;
        }
        index = Math.max(0,index);
        size++;
        ListNode pred = head;
        for(int i = 0;i<index;i++){
            pred = pred.next;
        }
        ListNode toAdd = new ListNode(val);
        toAdd.next = pred.next;
        pred.next = toAdd;
    }
    
    public void deleteAtIndex(int index) {
        if(index <0 || index >= size){
            return;
        }
        size--;
        ListNode pred = head;
        for(int i = 0;i<index;i++){
            pred = pred.next;
        }
        pred.next = pred.next.next;
    }
}

class ListNode{
    int val;
    ListNode next;
    
    public ListNode(int val){
        this.val = val;
    }
}

这道题,有一个要点在于addAtIndex()中循环i<=index.

206. 反转链表 - 力扣(LeetCode)

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode prev = null;
        ListNode curr = head;
        while(curr != null){
            ListNode next = curr.next;
            curr.next = prev;
            prev = curr ;
            curr = next ;
        }
        return prev;
    } 
}

好题,不知道自己学会没,以后可以复习一下,可能会有新的感悟。