初始化链表:
static class Node{
int val;
Node next;
Node(int data){
this.val = data;
this.next=null;
}
}
public static Node initLinkList(int[] array){
Node head = null,cur = null;
for(int i = 0;i < array.length;i++){
Node newNode = new Node(array[i]);
newNode.next=null;
if(i==0){
head=newNode;
cur=newNode;
}else{
cur.next=newNode;
cur=newNode;
}
}
return head;
}
反转方式一:用虚拟头结点实现反转
//虚拟头结点法来反转链表
public static Node reverseList(Node head){
Node ans=new Node(-1);
//ans.next=head;
Node cur=head;
while(cur!=null){
Node next=cur.next;
cur.next=ans.next;
ans.next=cur;
cur=next;
}
return ans.next;
}
方式一存疑:cur结点应该是指向head,还是指向head的下一个结点?
已解决:cur指向head,第一步中cur的下一个结点是空,注意看图!
方式二:直接操作链表,不用虚拟头结点
//直接操作链表,不使用虚拟头结点
public static Node reverseList2(Node head){
Node prev=null;
Node curr=head;
while(curr!=null){
Node next=curr.next;
curr.next=prev;
prev=curr;
curr=next;
}
return prev;
}
测试主函数:
public static void main(String[] args) {
int[] a={1,2,3,4,5};
Node head1 = initLinkList(a);
Node newHead = reverseList(head1);
System.out.println("value of newHead is :"+newHead.val);
System.out.println("old head value is :"+head1.val);
Node newHead2 = reverseList2(newHead);
System.out.println("value of newHead2 is :"+newHead2.val);
Node newHead3 = reverseList2(newHead2);
System.out.println("value of newHead3 is :"+newHead3.val);
/* Node newHead4 = reverseList3(newHead3);
System.out.println("value of newHead4 is :"+newHead4.val);*/
}