單鏈表反轉(zhuǎn)使用p、q疼进、r三個指針配合工作薪缆,使得兩個節(jié)點間的指向反向,同時用r記錄剩下的鏈表伞广〖鹈保基本流程如下圖所示:
public class ReverseList {
public static Node reverseList(Node head){
Node p = new Node(0);
Node q = new Node(0);
Node r = new Node(0);
p = head;
q = head.next;
p.next = null;
while(q!=null){
r = q.next;
q.next = p;
p = q;
q = r;
}
head = p;
return head;
}
public static void main(String[] args) {
int count = 9;
Node t = new Node(1);
Node x = t;
for(int i = 2; i <= count; i++){
x = (x.next = new Node(i));
}
t = reverseList(t);
while(t!=null){
System.out.print(t.val+" ");
t = t.next;
}
}
public static class Node{
int val;
Node next;
Node(int v){
val = v;
}
}
}
本文為作者kMacro原創(chuàng),轉(zhuǎn)載請注明來源:http://www.reibang.com/p/5043be2fc875嚼锄。