今天在中金所面试遇到了到简单但是却没重视的题目,结果写的像坨shi一样,回来再写一遍吧,基本思路就是倒转指针,用一个辅助指针先记录下来后驱,总共需要三个辅助指针,代码如下:
public class Size {
class No{
public int data;
public No next;
public No() {
// TODO Auto-generated constructor stub
data = 0;
next = null;
}
}
private No head;
Size(){
buildList();
}
public void buildList(){
head = new No();
head.data = 0;
No cur = head;
for(int i = 0; i < 10;i++){
No newNode = new No();
newNode.data = i+1;
cur.next = newNode;
cur = newNode;
}
}
void reverse(){
No pre,cur,lat;
pre = head;
cur = head.next;
while(cur!=null){
lat = cur.next;
cur.next = pre;
pre = cur;
cur = lat;
}
head.next = null;
head = pre;
}
public void showAll(){
No pNo = head;
while(pNo!=null){
System.out.print(pNo.data);
pNo = pNo.next;
}
System.out.println();
}
public static void main(String[] args) {
Size size = new Size();
size.showAll();
size.reverse();
size.showAll();
size.reverse();
size.showAll();
}
}