203. Remove Linked List Elements

来源:互联网 发布:sql优化工具 编辑:程序博客网 时间:2024/04/30 00:13

题目

Remove all elements from a linked list of integers that have valueval.

Example

Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6,val = 6

Return: 1 --> 2 --> 3 --> 4 --> 5

我的解法

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeElements(ListNode head, int val) {                // 获取res链表的头结点        ListNode res = null;         while(head != null){            if(head.val != val){                res = head;                head = head.next;                break;            }            head = head.next;        }        //  将头节点作为下个节点的前节点        ListNode pre = res;        while(head != null){            // 满足条件则插入前节点后,更新前节点            if(head.val != val){                pre.next = head;                pre = head;            }else            // 否则前节点插入Null(保证尾节点删除时正确,中间节点存在时不影响结果);不更新前节点                pre.next = null;            head = head.next;        }        return res;    }}

分析:正常思维,好理解。判断边界情况,即先判断head是否满足,然后迭代算法。

答案解法(和我的思路类似)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode removeElements(ListNode head, int val) {        // 假的头节点。当原链表head节点要删除时,保证后续的节点有“前节点”        ListNode fakeHead = new ListNode(-1);        ListNode pre = fakeHead;        while(head != null){            // prev节点后插入此节点            if(head.val != val){                pre.next = head;                pre = head;            }else            // prev节点后插入此节点的next节点                pre.next = head.next;            head = head.next;        }        return fakeHead.next;    }}

算法分析:和我的解法类似,但在一个细节上比我处理的好,即使用假的头结点,避免了寻找res链表的头结点;
不同点:使用pre.next = head.next 代替 pre.next = null,即不满足时就用节点的子节点代替,如果子节点满足则再重复插入一次;不满足时再用子节点的子节点代替;若到了尾节点,则head.next = null,和我的方法等效;

答案解法(递归)

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {       public ListNode removeElements(ListNode head, int val) {        if (head == null) return null;        // 对下一节点调用同样的方法        head.next = removeElements(head.next, val);        // 符合要求的节点是本节点or其下一节点;        return head.val == val ? head.next : head;    }}

分析:代码简介,但是不容易想到这个思路。

0 0