实现链表的翻转
public class ListNodeReverse {
public listNodeRe ReverseList(listNodeRe head) {
listNodeRe next = null;
listNodeRe pre = null;
while (head != null) {
next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
public static void main(String[] args) {
listNodeRe a = new listNodeRe(1);
listNodeRe b = new listNodeRe(2);
listNodeRe c = new listNodeRe(3);
listNodeRe d = new listNodeRe(4);
listNodeRe e = new listNodeRe(5);
a.next = b;
b.next = c;
c.next = d;
d.next = e;
ListNodeReverse l = new ListNodeReverse();
l.ReverseList(a);
while (e != null) {
System.out.println(e.val);
e = e.next;
}
}
}
总结:while循环中,你会发现他们围成一圈了, 为什么返回这个 return pre; 因为pre = head; 为什么这样输出, System.out.println(e.val); e = e.next;因为这样输出才能实现数字翻转。