链表的逆转也算是面试中比较常见的问题了,今天闲来无聊,就写了一下一个简单的实现。
这里我并没有用java里面的LinkedList类来写,而是自己写了个简单的链表结构,这里只是用来建一个链表,具体的操作方法并没有详写:
package normal;
public class LL {
public Node head;
class Node{
String value;
Node next;
public Node(String value){
this.value = value;
}
}
public LL(String[] arr){
if(arr.length != 0){
Node node = new Node(arr[0]);
this.head = node;
for(int i=1; i<arr.length; i++){
node.next = new Node(arr[i]);
node = node.next;
}
}
else
this.head = null;
}
public Node add(String value){
return head;
}
}
然后是具体的链表逆转的操作:
package normal;
import java.util.LinkedList;
import normal.LL.Node;
public class ReverseLL {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ReverseLL o = new ReverseLL();
LL ll = o.createLL();
Node node = o.reverse(ll);
}
private Node reverse(LL ll) {
// TODO Auto-generated method stub
Node pre = null;
Node cen = ll.head;
Node pos = cen.next;
while(cen!=null){
cen.next = pre;
pre = cen;
cen = pos;
if (pos!=null) pos = pos.next;
}
return pre;
}
public LL createLL(){
String[] arr = {"1","2","3","4","5"};
LL ll = new LL(arr);
return ll;
}
}
最后的node即是所得逆转链表的head节点。