• Remove Linked List Elements &&remove-duplicates-from-sorted-list


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

    样例

    Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5

    这道题的算法其实很简单,如果遇到要删除的元素,跳过,直接找到下一个非目标元素;无奈学渣的我对链表竟然已经到了如此退化的题目,所以也研究了一些时间。

     1 /**
     2  * Definition for singly-linked list.
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) { val = x; }
     7  * }
     8  */
     9 public class Solution {
    10     /**
    11      * @param head a ListNode
    12      * @param val an integer
    13      * @return a ListNode
    14      */
    15     public ListNode removeElements(ListNode head, int val) {
    16         // Write your code here
    17         ListNode helpnode = new ListNode (0);
    18         helpnode.next = head;
    19         ListNode p = helpnode;
    20         while(p.next != null){
    21             if(p.next.val == val){
    22                 p.next = p.next.next;
    23             }
    24             else {
    25                 p = p.next;
    26             }
    27         }
    28         return helpnode.next;
    29     }
    30 }

    拓展题:

    删除排序链表中的重复元素

    容易 删除排序链表中的重复元素

    给定一个排序链表,删除所有重复的元素每个元素只留下一个

    样例

    给出1->1->2->null,返回 1->2->null

    给出1->1->2->3->3->null,返回 1->2->3->null

     1 /**
     2  * Definition for ListNode
     3  * public class ListNode {
     4  *     int val;
     5  *     ListNode next;
     6  *     ListNode(int x) {
     7  *         val = x;
     8  *         next = null;
     9  *     }
    10  * }
    11  */
    12 public class Solution {
    13     /**
    14      * @param ListNode head is the head of the linked list
    15      * @return: ListNode head of linked list
    16      */
    17     public static ListNode deleteDuplicates(ListNode head) { 
    18         ListNode p = new ListNode(0);
    19         p.next = head;
    20         if(head == null )
    21            return null;
    22         while (head.next != null){
    23             if (head.next.val == head.val ){
    24                  head.next = head.next.next;
    25              }else{
    26              head = head.next;
    27              }
    28         }
    29         return  p.next;
    30     }  
    31 }
  • 相关阅读:
    P2422 良好的感觉
    拉格朗日插值
    C# 中的委托和事件(详解)
    异步委托
    ManualResetEvent详解
    快速理解C#高级概念事件与委托的区别
    拉格朗日多项式
    oracle 插入一个从别处查询获得字段的值
    decode和nvl的用法
    C#将像素值转换为图片
  • 原文地址:https://www.cnblogs.com/wangnanabuaa/p/4951578.html
Copyright © 2020-2023  润新知