反转单链表 本是古典 何须时尚 2022-11-30 01:46 308阅读 0赞 [https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking][https_www.nowcoder.com_practice_75e878df47f24fdc9dc3e400ec6058ca_tpId_13_rp_1_ru_2Fta_2Fcoding-interviews_qru_2Fta_2Fcoding-interviews_2Fquestion-ranking] ### 一、问题描述 ### 输入一个链表,反转链表后,输出新链表的表头。 ### 二、代码实现 ### /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { //迭代 public ListNode ReverseList(ListNode head) { if (head == null || head.next == null) { return head; } ListNode newHead = null; while (head != null) { //从原链表中删除头部一个元素cur ListNode cur = head; //cur.next = null; 这里无需这么做,在别处最好加上避免出现环 head = head.next; //将删除的元素cur添加到新链表中(采用头插法) cur.next = newHead; newHead = cur; } return newHead; } //递归 public ListNode ReverseList1(ListNode head) { if (head == null || head.next == null) { return head; } ListNode next = head.next; head.next = null; ListNode newHead = ReverseList(next); next.next = head; return newHead; } } [https_www.nowcoder.com_practice_75e878df47f24fdc9dc3e400ec6058ca_tpId_13_rp_1_ru_2Fta_2Fcoding-interviews_qru_2Fta_2Fcoding-interviews_2Fquestion-ranking]: https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&rp=1&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking
相关 单链表反转 常常面试我们会遇到考察列表反转的问题 如 1-->2-->3-->4-->5-->null这样的一个链表进行反转成为 null<--1<--2<--3<--4<--5 川长思鸟来/ 2023年06月25日 06:01/ 0 赞/ 2 阅读
相关 单链表反转 class Node{ int value; Node next; public Node(int value){ 淩亂°似流年/ 2023年06月24日 14:25/ 0 赞/ 2 阅读
相关 反转单链表 [https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&rp=1&ru=%2Ft 本是古典 何须时尚/ 2022年11月30日 01:46/ 0 赞/ 309 阅读
相关 单链表反转 include<iostream> using namespace std; typedef struct node { i 刺骨的言语ヽ痛彻心扉/ 2022年09月18日 04:47/ 0 赞/ 278 阅读
相关 单链表反转 public Node reverse(){ Node pReverseHead=null; Node pNode=head;//当前结点开始为 痛定思痛。/ 2022年08月10日 13:46/ 0 赞/ 305 阅读
相关 单链表反转 把每次翻转看成左右两个部分的翻转,比如第一次翻转时把左边的第一个节点看成左部分,把右边的第二个节点看成右部分,来进行翻转,第二次翻转时把左边的两个节点看成一个左部分,右边的第三 本是古典 何须时尚/ 2022年08月09日 01:55/ 0 赞/ 290 阅读
相关 反转单链表 前插 class ListNode { int val; ListNode next; ListNode(i Bertha 。/ 2022年08月04日 04:18/ 0 赞/ 306 阅读
相关 反转单链表 一、反转单链表 //反转单链表链表 class ListNode { int val; ListNode next = n Bertha 。/ 2022年05月26日 06:11/ 0 赞/ 280 阅读
相关 反转单链表 ![这里写图片描述][70] //解法一:反转链表 public ListNode reverseList(ListNode head){ 以你之姓@/ 2022年05月23日 04:36/ 0 赞/ 325 阅读
相关 单链表反转 单链表的翻转是一道很基本的算法题。 方法1:将单链表储存为数组,然后按照数组的索引逆序进行反转。 方法2:使用三个指针遍历单 悠悠/ 2022年03月09日 11:26/ 0 赞/ 364 阅读
还没有评论,来说两句吧...