题目:
将一个链表进行反转.
ListNode.java
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
this.next=null;
}
}
Solution.java
/**
* Created by xizwu on 2017/2/16.
*/
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
ListNode pre=null;
ListNode next=null;
while(head !=null){
next=head.next;
head.next=pre;
pre=head;
head=next;
}
return pre;
}
public ListNode insert(ListNode head,int val){
//1. 指向 链表的末尾
ListNode before=head;
if(head==null){
before=new ListNode(val);
return before;
}
while(head.next !=null){
head=head.next;
}
ListNode myNode=new ListNode(val);
head.next=myNode;
//2. 添加一个node
return before;
}
public void myprint(ListNode head){
if(head==null){
System.out.println(" The list is empty");
return;
}
while(head!=null){
System.out.print(head.val+" ");
head=head.next;
}
}
}
maintest.java
/**
* Created by xizwu on 2017/2/16.
*/
public class maintest {
public static void main(String[] args) {
Solution myso = new Solution();
ListNode myhead = null;
ListNode afterResverHead=null;
myhead=myso.insert(myhead, 1);
myhead=myso.insert(myhead, 2);
myhead=myso.insert(myhead, 3);
myso.myprint(myhead);
afterResverHead=myso.ReverseList(myhead);
System.out.println("#################");
myso.myprint(afterResverHead);
}
}
最后的结果:
1 2 3 #################
3 2 1