c/c++语言开发共享LeetCode(52)-Remove Linked List Elements

题目: remove all elements from a linked list of integers that have value val. example given: 1


题目:

  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

思路:

题意:有序列表里面去掉给定的元素遍历发现相同的,就去掉,prev.next != null,发现了prev.next = prev.next.next 考虑头部满足条件的情况,那就一直删除下去 –

代码:

  /**   * 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;          }          while(head.val == val){              head = head.next;              if(head == null){                  return null;              }          }          listnode prev = head;          while(prev.next != null){              while(prev.next.val == val){                  prev.next = prev.next.next;                  if(prev.next == null){                  return head;              }              }              prev = prev.next;          }          return head;      }  }

 

 

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/607647.html

(0)
上一篇 2021年5月14日
下一篇 2021年5月14日

精彩推荐