2 回答
TA贡献1775条经验 获得超11个赞
不,JavaLinkedList
不允许您直接在节点上工作。
如果你需要一个 O(1) 的“指针”,你可以使用 ListIterator:list.listIterator()
如果你的链表是一个自定义实现,我 99% 肯定这是你的作业,你应该自己做。
TA贡献1744条经验 获得超4个赞
public class Node {
public int data;
public Node next;
public Node(int _data) {
this.data = _data;
this.next = null;
}
public String toString() {
return (Integer.toString(data));
}
}
public class LinkedList {
public static void main(String args[]) {
LinkedList linkedlist = new LinkedList();
linkedlist.InsertNode(15);
linkedlist.InsertNode(20);
linkedlist.InsertNode(25);
linkedlist.InsertNode(30);
linkedlist.InsertNode(35);
linkedlist.showLinkedList();
System.out.println("\n");
Node retnode = linkedlist.retPosNode(2);
System.out.println("REturn Node: "+retnode.data);
linkedlist.showLinkedList();
}
Node head;
public void InsertNode(int data) {
Node node = new Node(data);
if (head == null) {
head = node;
} else {
Node n = head;
while (n.next != null) {
n = n.next;
}
n.next = node;
}
}
public Node retPosNode(int pos) {
Node curr = head;
Node prev= null;
Node retPos= null;
int i=0;
if (curr==null)
return null;
while(curr!=null) {
if(i==pos) {
if(i!=0) {
retPos = curr;
prev.next= curr.next;
curr = curr.next;
}
else {
retPos = curr;
head= curr.next;
curr = curr.next;
}
}
prev= curr;
curr = curr.next;
i++;
}
return retPos;
}
public void showLinkedList() {
Node node = head;
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
}
}
添加回答
举报