从链表中删除大于指定值的节点

时间:2017-04-09 18:05:54

标签: algorithm linked-list

给定一个整数值和指向链表头部的指针,如何从列表中删除大于指定值的所有节点?

e.g。

列表:10-> 34-> 11-> 19-> 26-> 55-> 17 价值:19 输出:10-> 11-> 17(需要删除所有大于19的节点)

(边缘案例)

列表:10-> 3-> 17-> 5-> 2-> 14-> 7 价值:9 输出:3-> 5-> 2-> 7(需要删除所有大于9的节点)

我不是在寻找确切的代码,只是一种算法来解决这个问题!

4 个答案:

答案 0 :(得分:3)

private static Node removeNodes(Node start, int x) {

if(start == null) return start;

if(start.data > x && start.next == null) return null;

//find first head node
Node cur = start;
Node prev = null;

//4,5,3,2,1,6 --- where x = 2
while(cur != null && cur.data > x) {
    prev = cur;
    cur = cur.next;
}

if(prev != null) prev.next = null;

Node newHead = cur;

while(cur.next != null) {
    if(cur.next.data > x) {
        cur.next = cur.next.next;
    } else {
        cur = cur.next;
    }
}

return newHead;
}

答案 1 :(得分:2)

首先将临时节点分配给起始节点
然后你在链表中有三个案例
如果第一个位置的所需节点然后使开始等于start->next并删除临时节点
如果它在中间,则在temp之前使另一个节点停止,并使该节点的下一个节点等于下一个temp,然后delete temp
如果它在最后一个位置,则使它之前的下一个节点等于nullptr,就是这样。

答案 2 :(得分:0)

可以使用上一个和当前两个指针来解决这个问题,我想这个解决方案行之有效。

public static ListNode removeNode(ListNode head,int value){

        //removing every element whose Node value is greter than given value
        if(head==null) { return head;}

        ListNode current=head;
        ListNode previous=new ListNode(0);
        previous.next=current;


        while(current!=null){               
            //System.out.println("current value; "+current.val);
            if(current.val>=value){
                if(current.next==null){
                    current=null;
                }
                else {
                current=current.next;}
                previous.next=current;
            }           
            else {
            previous=previous.next;
            current=current.next;
            }
        }
        return head;
      }

答案 3 :(得分:-1)

enter image description here Consider the picture here .Suppose we have to delete the node which is greater than 8 and we have Head Pointer pointing to head of the list.First we will take two pointers Prev and temp both points to head initially.Then through the pointer we will traverse the list and keep track the current and prev pointers in temp and Prev.If current number is greater than 8 Prev will point to the next node pointed by temp and temp node will be deleted.By traversing all the node and following this rule you can delete the specified node of the list.... I hope you got the point........