int len = link.size(); while(len > 0){ link.poolLast(link.offerFirst()); --len; }
随手写的,没有编译没有运行过,只是个思路而已 要是不知道那个方法是干啥的可以看一下api
Collections public static void reverse(List<?> list)
多谢。我下面这个参考了你的思路,但有点笨 public LinkedList reverse(LinkedList ll){ LinkedList llResault = new LinkedList(); int len = ll.size(); while (len > 0) { llResault.add(ll.pollLast()); --len; } return llResault;
}
没看懂?大师能帮我改一下上面的CODE吗? 我不太会用<?>
谁能看懂下面的CODE?晕哪 public class MyLinkedList { Node first, last = null; class Node { public int data; public Node next; }
void addNode(int data) { Node myNode = new Node(); myNode.data = data; myNode.next =null; if (first == null) first = myNode; if (last != null) last.next = myNode; last = myNode; }
public void reverse() {
if (null == first) return;
Node p = null; Node c = first; Node n = c.next;
c.next = p; while (n != null) { p = c; c = n; n = n.next; c.next = p; }
while(len > 0){
link.poolLast(link.offerFirst());
--len;
}
要是不知道那个方法是干啥的可以看一下api
public static void reverse(List<?> list)
多谢。我下面这个参考了你的思路,但有点笨 public LinkedList reverse(LinkedList ll){
LinkedList llResault = new LinkedList();
int len = ll.size();
while (len > 0) {
llResault.add(ll.pollLast());
--len;
}
return llResault;
}
public class MyLinkedList {
Node first, last = null; class Node {
public int data;
public Node next;
}
void addNode(int data) {
Node myNode = new Node();
myNode.data = data;
myNode.next =null; if (first == null)
first = myNode;
if (last != null)
last.next = myNode;
last = myNode;
}
public void reverse() {
if (null == first)
return;
Node p = null;
Node c = first;
Node n = c.next;
c.next = p;
while (n != null) {
p = c; c = n; n = n.next; c.next = p;
}
Node t = first;
first = last;
last = t;
}
void print() {
for (Node myNode = first; myNode != null ; myNode = myNode.next )
System.out.print(myNode.data +",");
} //---------------------main()--------------------------
public static void main(String[] args) {
MyLinkedList myLinkedList = new MyLinkedList(); myLinkedList.addNode(1);
myLinkedList.addNode(2);
myLinkedList.addNode(3);
myLinkedList.addNode(4);
myLinkedList.addNode(5);
myLinkedList.print();
myLinkedList.reverse();
System.out.println();
myLinkedList.print();
}
}
以前学C语言的时候写的和这个相似
java有已经实现了的,直接用就好了
如果是想了解链表看一下数据结构
改成这样,我就懂了 Node previous = null;
Node current = first;
Node next = current.nextNode;
current.nextNode = null;
while (next != null) {
previous = current;
current = next;
next = next.nextNode;
current.nextNode = previous;
}
Node tep = first;
first = last;
last = tep;