zoukankan      html  css  js  c++  java
  • LeetCode OJ :Remove Linked List Elements (移除链表元素)

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

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

    ps:这一题感觉没什么技巧可言,选取一个头指针,一个当前指针,一个前向指针。简单的链表操作而已,代码如下:

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* removeElements(ListNode* head, int val) {
    12         ListNode * root = head;
    13         ListNode * prev = head;
    14         ListNode * curr = head;
    15         while (curr != NULL){
    16             if (curr->val == val){
    17                 if (prev == curr)
    18                     root = prev = curr = curr->next;
    19                 else{
    20                     curr = curr->next;
    21                     prev->next = curr;
    22                 }
    23             }else{
    24                 prev = curr;
    25                 curr = curr->next;
    26             }
    27         }
    28         return root;
    29     }
    30 };

     java版本如下所示:

     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     public ListNode removeElements(ListNode head, int val) {
    11         while(head != null && head.val == val){
    12             ListNode helper = head;
    13             head = head.next;
    14             helper.next = null;
    15         }
    16         if(head == null)
    17             return head;
    18         ListNode p1 = head;
    19         while(p1.next != null){
    20             if(p1.next.val == val){
    21                 p1.next = p1.next.next;
    22             }else
    23                 p1 = p1.next;
    24         }
    25         return head;
    26     }
    27 }
  • 相关阅读:
    html background 背景颜色美化 类似毛玻璃
    HTML
    export、exports、modules.exports 和 require 、import 的一些组合套路和坑
    C#实现监控网络流量
    PHP乱码问题,UTF-8(乱码)
    LitDB笔记
    LitDB文章
    NoSQL 35 个非主流数据库
    mysql中int转varchar
    CSS设置DIV背景色渐变显示
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/4855151.html
Copyright © 2011-2022 走看看