剑指offer——反转链表
1 题目描述
输入一个链表,反转链表后,输出链表的所有元素。
2 答案一:利用栈
思路1:遍历链表,将链表的所有元素存入一个栈中,从栈中取出元素时,依次得到的就是原链表从尾到头的节点。代码如下:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.Stack;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
Stack<ListNode> stack = new Stack<ListNode>();
while(head!=null){
stack.push(head);
head=head.next;
}
ListNode newhead=stack.pop();
ListNode resulthead=newhead;
while(!stack.isEmpty()){
newhead.next=stack.pop();
newhead=newhead.next;
}
newhead.next=null;//该语句一定不要忘记,否则会造成错误。
return resulthead;
}
}
3 答案二:只遍历一次,改变节点的指向,不利用新的结构
思路2:依次遍历所有节点,将所有节点的next指向前一个节点,代码如下:
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode ReverseList(ListNode head) {
ListNode pre=null;//前一个节点
ListNode next=null;//后一个节点
while(head!=null){
next=head.next;//当前节点的下一个节点保存下来
head.next=pre;//当前节点指向前一个节点
pre=head;//更新前一个节点值,顺序不能相反
head=next;//更新当前节点值,顺序不能相反
}
return pre;//一定要注意此处不是返回head,因为此时head为null
}
}