面16
题目描述
输入一个链表,反转链表后,输出链表的所有元素。
思路:
一开始想到用递归做,因为递归的代码更加简洁(但我一开始没想出来好的递归方法,所以先用了普通的循环…),主要还是考虑一些边界的情况。
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
if(head.next==null)
return head;
ListNode before = head;
ListNode now = head.next;
ListNode after = now.next;
head.next = null;
while(after!=null){
now.next = before;
before = now;
now = after;
after = now.next;
}
now.next = before;
return now;
}
// 循环的代码量稍多一些,但不需要担心栈溢出的情况
// 在纸上画一下链表,基本就能把需要考虑到的东西都写出来
递归的方法,要设置一个新的头节点(之前提交过的答案,结果现在写不出来了…)
public class Solution {
ListNode newHead = null; //定义一个全局变量
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
helper(head);
return newHead;
}
private ListNode helper(ListNode head){
if(head.next!=null){
helper(head.next).next = head;
head.next = null; //主要是为了让原链表的头节点的next节点为null
}
else
newHead = head; // 当head.next==null,说明已经走到原链表的末尾,此节点为反转后的头结点
return head;
}
}
循环的其他写法
public ListNode ReverseList(ListNode head) {
if(head==null)
return null;
//head为当前节点,如果当前节点为空的话,那就什么也不做,直接返回null;
ListNode pre = null;
ListNode next = null;
//当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点
//需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2
//即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
//所以需要用到pre和next两个节点
//1->2->3->4->5
//1<-2<-3 4->5
while(head!=null){
//做循环,如果当前节点不为空的话,始终执行此循环,此循环的目的就是让当前节点从指向next到指向pre
//如此就可以做到反转链表的效果
//先用next保存head的下一个节点的信息,保证单链表不会因为失去head节点的原next节点而就此断裂
next = head.next;
//保存完next,就可以让head从指向next变成指向pre了,代码如下
head.next = pre;
//head指向pre后,就继续依次反转下一个节点
//让pre,head,next依次向后移动一个节点,继续下一次的指针反转
pre = head;
head = next;
}
//如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
//直接输出pre就是我们想要得到的反转后的链表
return pre;
}
2020-12-16
只能想出最笨的stack方法了。。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(null == head){
return null;
}
Stack<ListNode> stack = new Stack<>();
while(null != head){
stack.push(head);
head = head.next;
}
ListNode result = stack.peek();
while(stack.size() > 1){
stack.pop().next = stack.peek();
}
stack.pop().next = null;
return result;
}
}
注意nowcoder上是要自己写import的
import java.util.*;
public class Solution {
public ListNode ReverseList(ListNode head) {
if(null == head || null == head.next){
return head;
}
ListNode now = head;
ListNode pre = null;
ListNode after = head.next;
while(null != after){
now.next = pre;
pre = now;
now = after;
after = after.next;
}
now.next = pre;
return now;
}
}