https://leetcode-cn.com/problems/UHnkqh/
https://leetcode-cn.com/problems/reverse-linked-list/
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head; //这里的头结点值为1。不是空
System.out.println(head.val);
while(cur!=null){ //主要是对cur进行的操作,所以,cur不为空就行,画个图就明白了
//记得来时的路,记录当前节点的原始下一个节点
ListNode next = cur.next;
//让当前节点的下一个指向其前一个
cur.next = pre;
//然后开始迭代
pre=cur;
cur=next;
}
System.out.println(pre.val);
return pre;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode cur = head;
//反转后的尾
ListNode pre = null;
//存放来时的路
ListNode temp = null;
while(cur!=null){
//已经存了来时的路
temp = cur.next;
//开始修改指针的指向
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}
2,递归
一般链表题都可以采用迭代法和递归法
翻转,只需要将curr.next = prev
对于每个节点都是这样的操作,就是迭代了
但是当你将下一个节点指向前一个的时候,链表就断开了
所以,你需要首先把链表的下一个节点记录下来
这段代码的一个错误解决方式
主要是我忘记了:尾节点应该指向null的!
问题解决参考链接:
206. 反转链表(Error - Found cycle in the ListNode)
递归解法
链表非常符合递归的解法,因为很容易满足递归的条件
可以把问题拆解为头结点和其他结点两个问题
递归代码解释:
递归代码分为递过程和归过程,
递过程就是将大问题拆解成小问题的过程
归过程要有反转动作
【1】最小子问题就是递归终止条件
【2】之后返回一个反转后的链表
【3】归过程,发生在递归调用之后,后面是归要做的事情
【1】是递要做的事情
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
//先写终止条件
if(head==null||head.next==null){
return head;
}
ListNode p = reverseList(head.next);
head.next.next=head;
head.next=null;
return p;
}
}
参考链接:
https://leetcode-cn.com/problems/reverse-linked-list/
https://leetcode-cn.com/problems/reverse-linked-list/solution/shi-pin-jiang-jie-die-dai-he-di-gui-hen-hswxy/
https://blog.youkuaiyun.com/qq_45759413/article/details/121470865
微信公众号:抖码课堂