簡體   English   中英

刪除鏈表的最后一個節點

[英]Delete Last Node of a Linked List

我正在練習使用鏈表節點,但遇到了一個我不知道如何回答的問題。 你如何刪除鏈表中的最后一個節點。 下面的代碼適用於最后一個節點的所有條目欄。 最后一個不會被刪除。

節點類

public class Node {

    private String data;
    private Node next;

    Node(String data, Node next)
    {
        this.data = data;
        this.next = next;
    }

    public void setData(String d)
    {
        data = d;
    }

    public void setNext(Node n)
    {
        next = n;
    }

    public String getData()
    {
        return data;
    }

    public Node getNext()
    {
        return next;
    }

主要的

Node list = new Node("NODE 1",new Node("NODE 2",new Node("NODE 3", null)));
        list = insertSecond(list,"New Node");
        list = addLast(list,"LAST NODE");

        printList(list);
        System.out.println();
        deleteNode(list,"LAST NODE");
        printList(list);    
    }

    public static Node deleteNode(Node list,String str)
    {
        Node temp = list;
        Node prev = list;

        while(temp.getNext() != null)
        {
            if(temp.getData().equals(str))
            {
                if(prev.getNext() == null)
                    prev.setNext(null);
                else{
                prev.setNext(prev.getNext().getNext());
                }

            }
            prev = temp;
            temp = temp.getNext();
        }
while(temp != null){
  prev = temp;
  temp = temp.getNext();

}

prev.next = null;

嘗試這個:

這是我用來刪除最后一個節點的非常簡單的技術。

public void deleteLast() {
    Node curr = null;

    for (curr = this.first; curr.next.next != null;curr = curr.next) {

    }

    curr.next = null;
}

如果您使用雙向鏈接列表,則最簡單,您的列表知道開始和結束。

然后你可以做這樣的事情:

public void removeLastItem(){
    this.lastNode = this.lastNode.prev;
}

我猜你的最后一個元素while(temp.getNext() != null)失敗。 最后一個元素不會有next元素。 所以最后一個元素不會與傳遞的字符串進行比較。 您應該使用調試器來跟蹤它。

你需要這樣的東西:

public static Node deleteNode(Node list, String str) {
  Node temp = list;
  Node prev = list;

  do {
    if (temp.getData().equals(str)) {
      if (prev.getNext() == null) {
        prev.setNext(null);
      } else {
        prev.setNext(prev.getNext().getNext());
      }
    }
    prev = temp;
    temp = temp.getNext();
  } while (temp != null);

  return list;
}

您過早地停止循環。

BTW: if (prev.getNext() == null) { prev.setNext(null); ... if (prev.getNext() == null) { prev.setNext(null); ...沒有意義,但我會把那個錯誤留給你。

刪除單向鏈表中的節點

假設

  1. 列表中的每個節點都有一個nextNode指針。
  2. headOfList指針指向列表中的第一個節點。
  3. 已經在鏈表中的每個節點的下一個指針是正確的。
  4. 列表中最后一個節點的下一個指針是一些有意義的值(例如,null)。

實施步驟

  1. 如果列表為空,則完成。 未找到所需節點。
  2. 如果第一個節點是所需節點,則將headOfList指針設置為headOfList->nextNode值。 完畢。 找到所需的節點。
  3. currentNode指針設置為headOfList指針值。
  4. 如果currentNode節點是最后一個節點。 完畢。 未找到所需節點。
  5. 如果currentNode->nextNode節點是所需節點,則將currentNode->nextNode設置為currentNode->nextNode->nextNode值。 完畢。 找到所需的節點。
  6. 轉到第 4 步。

筆記

由於這是一個單向鏈表,您無法備份。 因此,您需要指向節點父節點並檢查節點子節點是否是您要刪除的節點。 會有邊界條件。

一些代碼

這是 LinkedList 類的成員函數。 startOfList 是一個類成員,指向鏈表的開頭。

 public boolean delete(final String target)
    {
        if (startOfList != null)
        {
            if (StringUtils.equals(startOfList.getData(), target))
            {
                startOfList = startOfList.getNext();
                return true;
            }

            Node current = startOfList;

            for (Node next = current.getNext(); next != null; next = current.getNext())
            {
                if (StringUtils.equals(next.getData(), target))
                {
                    current.setNext(next.getNext());
                    return true;
                }
                else // advance one node.
                {
                    current = next;
                }
            }
        }

        return false;
    }

這是我的嘗試,假設最后一個節點的下一個變量將始終為空:

public class LastNodeRemoval {

  private static class Node {
      String item;
      Node next;
  }

  public static void main(String[] args) {
      Node third = new Node();
      third.item = "Third";

      Node second = new Node();
      second.item = "Second";
      second.next = third;

      Node first = new Node();
      first.item = "First";
      first.next = second;

      removalLastNode(first);
   }

   private static void removalLastNode(Node first) {
      Node temp = first;

      while(temp.next.next != null) {
          temp = temp.next;
      }

      temp.next = null;

      System.out.println("Last node: "+temp.item);
   }

}

這可以通過使用 Java 容器類“LinkedList”以更簡單的方式完成。 Java 中的 LinkedList 類實現了 Deque(雙端隊列)接口,該接口支持 get/add/remove First/Last 方法。 一個基本的代碼片段如下:

LinkedList<Integer> list = new LinkedList<Integer>();
list.addFirst(1);
list.addLast(2);
System.out.println(list.removeLast());

這個對我有用..

public void removeLastNode(){
    System.out.println("\n Inside removeLastNode");
    next=firstLink;
    prev=firstLink;
    if(next == null) System.out.println("\n The link List is Empty");
    while(next.getNext()!=null) { 
        prev=next;
        next=next.getNext();
    }
    prev.setNext(null);  
}

這里的邏輯很簡單,和獲取最后一個節點是一樣的。 這里的棘手之處在於,當您到達最后一個節點時,您必須記住最后一個節點之前的節點並將其設置為 null,以便它將成為新的最后一個節點。 在下面的代碼中,當您到達最后一個元素n2 時,獲取n1並將其設置為 null。

public void removeLast(){
    if(head==null) System.out.println("List is empty");
    else {
    Node n1 = null;
    Node n2 = head;
        while(n2.next != null)
        {
            n1 = n2;
            n2 = n2.next;
        }
        n1.next = null;
    }
public  Node deleteEnd(Node node)

{

if(node==null)

{

  throw new IllegalStateException();

}

    if(node.getNext()==null)
    return null;

    Node headF=node;

    while (node.getNext().getNext()!=null)
    {
        node=node.getNext();
    }
    node.setNext(null);
    return headF;

}

給定以下單鏈表實現,可以使用從第first節點開始遍歷列表的removeLast()removeLastRecursive()方法刪除最后first節點:

public class LinkedList<T> {
    Node<T> first;
    Node<T> last;
    int length;

    public LinkedList() {

    }

    public static void main(String[] args) {
        LinkedList<String> linkedList = new LinkedList();
        linkedList.add("A");
        linkedList.add("B");
        linkedList.add("C");
        linkedList.add("D");

        linkedList.printListParams();
        linkedList.removeLast();
        linkedList.printListParams();
        linkedList.removeLast();
        linkedList.printListParams();
        linkedList.removeLast();
        linkedList.printListParams();
        linkedList.removeLast();
        linkedList.printListParams();
        linkedList.removeLast();
        linkedList.printListParams();
    }

    public void add(T data) {
        if (isEmpty()) {
            first = new Node(data);
            last = first;
        } else {
            last.next = new Node(data);
            last = last.next;
        }
        length++;
    }

    public void removeLast() {
        Node current = first;
        if (isEmpty()) return;
        if (current.next != null) {
            while (current.next != null) {
                if (current.next.next == null) {
                    current.next = null;
                    last = current;
                    length--;
                    return;
                }
                current = current.next;
            }
        } else {
            first = null;
            last = null;
            length--;
        }
    }

    public void removeLastRecursive() {
        if (isEmpty()) return;
        if (first.next != null) {
            removeLast(first);
        } else {
            first = null;
            last = null;
            length--;
        }
    }

    private void removeLast(Node node) {
        if (node.next.next != null) {
            removeLast(node.next);
        } else {
            node.next = null;
            last = node;
            length--;
            return;
        }
    }

    public boolean isEmpty() {
        return first == null;
    }

    public void printList() {
        Node current = first;
        while (current != null) {
            System.out.print(current.data);
            current = current.next;
        }
        System.out.println();
    }

    public void printListParams() {
        printList();
        System.out.println("Length: " + length);
        System.out.println("Last node data: " + ((last != null) ? last.data : last));
        System.out.println("***********************");
    }

    private class Node<T> {
        T data;
        Node next;

        public Node(T data) {
            this.data = data;
        }
    }

}

/**
 * Deletion From End
 */
public static LinkedList DeletionFromEnd(LinkedList list){
    Node currNode = list.head;
    Node prevNode = null;

    while( currNode.getNext() != null) {
        prevNode = currNode;
        currNode = currNode.getNext();
    }
    prevNode.setNext(null);

    return list;
}

這將工作:)

public void deleteFromLast()
{   Node secondLastNode=null;
    Node currentNode=first;
    while(currentNode.next!=null)
    {   secondLastNode=currentNode;
        currentNode=currentNode.next;
        if(currentNode.next==null)
        {
            secondLastNode.next=null;;
            break;
        }
    }
}
這是更簡單和完美的工作方式。
public void deleteLastNode() {
    Node curr = head;
    Node prevNode = null;
    if(head == null) return;
    while(curr != null && curr.next != null) {
        prevNode = curr;
        curr = curr.next;
    }
    if(head.next != null) prevNode.next = null;
    else head = null;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM