在此记录一下java版的链表逆置,作为之前踩过的坑,希望以后都能记住。
包含逆置方法和测试方法,可以直接运行测试。
class Node {
int val;
Node next;
Node(int x){
this.val = x;
}
}
public class NodeReverse{
public static void main(String[] args){
Node head = init();
print(head);
head = reverse(head);
print(head);
}
//create the node list
public static Node init(){
Node cur = new Node(0);
Node head = cur;
Node node;
for(int i=1;i<=10;i++){
node = new Node(i);
cur.next = node;
cur = node;
}
return head;
}
//reverse the node list
public static Node reverse(Node head){
Node prev = null,tmp;
while(head!=null){
tmp = head.next;
head.next = prev;
prev = head;
head = tmp;
}
return prev;
}
//print the node list
public static void print(Node head){
while(head!=null){
System.out.print(head.val+",");
head = head.next;
}
System.out.println();
}
}
网友评论