206.反转一个单链表。
创建一个栈存储链表元素,进栈在出栈,存入新建的链表。
import java.util.Stack;
public class ConvertLianbiao {
public static void main(String[] args) {
ListNode a=new ListNode(2);
ListNode b=new ListNode(4);
b.next=new ListNode(3);
a.next=b;
ListNode er=reverseList(a);
while (er!=null){
System.out.println(er.val);
er=er.next;
}
}
public static ListNode reverseList(ListNode head) {
ListNode res=null;
ListNode root=null;
Stack<Integer> st=new Stack<Integer>();
while(head!=null){
st.push(head.val);
head=head.next;
}
while(!(st.isEmpty())){
int x=st.pop();
if(res==null){
//System.out.println(x);
root=res=new ListNode(x);
System.out.println(res.val);
}else{
//System.out.println(x);
res.next=new ListNode(x);
res=res.next;
}
}
return root;
}
}
采用头插法:
public ListNode reverseList(ListNode head) {
ListNode res=null;
while(head!=null){
if(res==null){
res=new ListNode(head.val);
head=head.next;
}else{
ListNode ss=new ListNode(head.val);
ss.next=res;
res=ss;
head=head.next;
}
}
return res;
}