Tag: singly linked list

迭代地反转单链表

必须是O(n)和就地(空间复杂度为1)。 下面的代码确实有效,但有更简单或更好的方法吗? public void invert() { if (this.getHead() == null) return; if (this.getHead().getNext() == null) return; //this method should reverse the order of this linked list in O(n) time Node prevNode = this.getHead().getNext(); Node nextNode = this.getHead().getNext().getNext(); prevNode.setNext(this.getHead()); this.getHead().setNext(nextNode); nextNode = nextNode.getNext(); while (this.getHead().getNext() != null) { this.getHead().getNext().setNext(prevNode); prevNode = this.getHead().getNext(); this.getHead().setNext(nextNode); if (nextNode != […]

如何从java中的链表中删除对象?

我的代码有一个问题,我做了一个示例程序来显示链接列表中的emp详细信息,现在问题当我试图删除一个特定条目意味着它不起作用,我希望我在我的代码中做了一些错误你能建议怎么做吗? import java.util.*; class EmpDedup { int record; String fprint; int fid; EmpDedup(int record, String fprint, int fid) { this.record = record; this.fprint = fprint; this.fid = fid; } public int getRecord() { return record; } public String getFprint() { return fprint; } public int getFid() { return fid; } public static void main(String[] args) […]

从未排序的链接列表中删除重复项

import java.util.*; /* * Remove duplicates from an unsorted linked list */ public class LinkedListNode { public int data; public LinkedListNode next; public LinkedListNode(int data) { this.data = data; } } public class Task { public static void deleteDups(LinkedListNode head){ Hashtable table=new Hashtable(); LinkedListNode previous=null; //nth node is not null while(head!=null){ //have duplicate if(table.containsKey(head.data)){ //skip […]

如何撤消链表?

Node reverse(Node head) { Node previous = null; Node current = head; Node forward; while (current != null) { forward = current.next; current.next = previous; previous = current; current = forward; } return previous; } 究竟是如何扭转名单的呢? 我知道它首先将第二个节点设置为forward 。 然后它说current.next等于前一个null节点。 然后它说previous现在是current 。 最后current变得forward ? 我似乎无法掌握这一点以及它的逆转方式。 有人可以解释这是如何工作的?

反向单链表Java

有人能告诉我为什么我的代码有效吗? 我想在java中反转单个链表:这是方法(不能正常工作) public void reverseList(){ Node before = null; Node tmp = head; Node next = tmp.next; while(tmp != null){ if(next == null) return; tmp.next = before; before = tmp; tmp = next; next = next.next; } } 这是Node类: public class Node{ public int data; public Node next; public Node(int data, Node next){ this.data = […]