day03 链表part01

203.移除链表元素 

使用dummy辅助, 使用cur来遍历

cur遍历到要操作节点的前一个节点。

class Solution {
    public ListNode removeElements(ListNode head, int val) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode cur = dummy;
        // 循环到链表结束
        while(cur.next != null){
            if(cur.next.val == val){
                // 值相等, 需要剔除
                cur.next = cur.next.next;
            }else{
                //不匹配
                cur = cur.next;
            }
        }
        return dummy.next;
    }
}

707.设计链表 

技巧,使用dummy来辅助操作。  使用cur遍历下去。

cur都是遍历到要操作的index之前,方便对节点操作。断链或者接链


class MyLinkedList {

    ListNode dummy;
    int size = 0;

    public MyLinkedList() {
        dummy = new ListNode(0);
    }
    
    public int get(int index) {
       if (index < 0 || index >= size){
        // 下标无效,返回-1
        return -1;
       }
       ListNode cur = dummy;
       while(index >=0){
        cur = cur.next;
        index--;
       }
       return cur.val;

    }
    
    public void addAtHead(int val) {
        ListNode newNode = new ListNode(val);
        newNode.next = dummy.next;
        dummy.next = newNode;
        size++;
    }
    
    public void addAtTail(int val) {
        ListNode newNode = new ListNode(val);
        ListNode cur = dummy;
        while(cur.next != null){
            // 遍历到链表尾
            cur = cur.next;
        }
        cur.next = newNode;
        size++;
    }
    
    public void addAtIndex(int index, int val) {
        if(index <0 || index > size){
            return;
        }
        ListNode newNode = new ListNode(val);
        ListNode cur = dummy;
        while(index > 0){
            // 遍历到index之前1个。
            cur = cur.next;
            index--;
        }
        newNode.next = cur.next;
        cur.next = newNode;
        size++;
    }
    
    public void deleteAtIndex(int index) {
        if (index < 0 || index >= size){
            return;
        }
        ListNode cur = dummy;
        while(index > 0){
            // 遍历到index之前1个,方便操作
            cur = cur.next;
            index--;
        }
        cur.next = cur.next.next;
        size--;
    }
}

206.反转链表

dfs,确定好终止条件

class Solution {
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next  == null){
            return head;
        }
        // 递归反转链表
        ListNode result = reverseList(head.next);
        // 把head接到最后。
        head.next.next = head;
        // 断开原来连接。
        head.next = null;
        return result;

    }
}

你可能感兴趣的:(链表,数据结构)