从单链表中删除元素(C ++)

时间:2017-10-21 23:10:20

标签: c++ algorithm

给定单个链接的整数列表l和整数k,如何从列表l中删除值为k的所有元素?优选在O(n)时间内。这就是我所拥有的:

$scope.deleteAlert= function(i){
    delete $scope.alertas[i];

}

任何提示?

2 个答案:

答案 0 :(得分:2)

这个怎么样?

ListNode1<int> * removeKFromList(ListNode1<int> * l, int k) {
          ListNode1<int> *tmp = l,*prev=NULL;
          if (l==NULL) return l;
          while (tmp) {
              if (tmp->value == k)
              {
                  if (prev)
                      prev->next=tmp->next;
                  else
                      l=l->next;
                  //delete tmp; ??
              }
              else
                  prev=tmp;

              tmp=tmp->next;
          }
          return l;
      }

答案 1 :(得分:0)

def removeKFromList(l, k):
    if(l is None):
        return l
    curr = l
    final = ListNode(0)
    i = 1
    newhead = l
    while(curr):
        if(curr.value != k and i):
            i = 0
            newhead = curr
        if(curr.value == k):
            final.next = curr.next
            tmp = final.next
            if(tmp is None and i):
                return None
        else:
            final = curr
        curr = curr.next
    return newhead