注意:
输入参数:链表头指针为null
或者链表中只有一个节点
的用例。
测试用例:
- null
- 只有一个节点
- 多个节点
import BrushProblem.swordOffer2.ListNode;
import java.util.Stack;
/**
* @Auther:
* @Date: 2018/11/6 18:38
* @Description: 反转链表
*/
public class ReverseList {
public static void main(String[] args) {
ListNode listNode=new ListNode(1);
ListNode listNode2=new ListNode(2);
ListNode listNode3=new ListNode(3);
listNode.next=listNode2;
listNode2.next=listNode3;
ReverseList obj=new ReverseList();
ListNode res=obj.ReverseList3(listNode);
}
/*
* 剑指offer思路 112页
* 定义3个节点
* 分别指向:当前节点,当前节点的前一个节点,当前节点的后一个节点
*
* */
public ListNode ReverseList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode pre=null;
ListNode cur=head;
ListNode next=cur.next;
while (cur!=null){
next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
public ListNode ReverseList2(ListNode head) {
//这里最好前面写上<ListNode>,new后面可以不写,不然后面pop出来的数据是object类型的
Stack<ListNode> stack=new Stack<>();
while (head!=null){
stack.push(head);
head=head.next;
}
if(stack.isEmpty()){
return null;
}
ListNode newHead=stack.pop();
ListNode cur=newHead;
while (!stack.isEmpty()){
cur.next=stack.pop();
cur=cur.next;
}
//这里一定要设置cur.next=null,因为不设置的话,cur.next不是空的。
//例如输入用例为:4->5
// head=cur=5
// cur.next=4,cur=cur.next,即cur=4,这时cur的next是5,5的next是4,就成了死循环
cur.next=null;
return newHead;
}
//因为方法2基于栈,而递归的本质就是一个栈结构,所以也可以用递归结决问题
ListNode result=new ListNode(0);
ListNode cur=result;
public ListNode ReverseList3(ListNode head) {
if(head==null||head.next==null){
return head;
}
recursive(head);
cur.next=null;
return result.next;
}
private void recursive(ListNode node){
if(node.next!=null){
recursive(node.next);
}
cur.next=node;
cur=cur.next;
}
}