您的位置:首页 > 教育 > 培训 > 网站建设合同属于_演员王野天_seo排名优化app_seo分析工具有哪些

网站建设合同属于_演员王野天_seo排名优化app_seo分析工具有哪些

2025/2/26 18:17:12 来源:https://blog.csdn.net/m0_73456341/article/details/143176095  浏览:    关键词:网站建设合同属于_演员王野天_seo排名优化app_seo分析工具有哪些
网站建设合同属于_演员王野天_seo排名优化app_seo分析工具有哪些

题目链接

反转链表

方法一:迭代

循环从第二个节点开始。

首先判断若没节点head为null 或者 若只有一个节点。head.next = null。则返回head。

接下来

定义一个 cur 节点,指向链表的第二个节点。这个 cur 将用于遍历链表。

将当前 head 节点的 next 设为 null,因为它将成为反转链表的末尾节点。

之后

开始遍历链表并反转指针

1.ListNode curNext = cur.next;   保存cur.next的值,防止丢失。

2.cur.next = head  反转链表。令cur.next指向前一个节点

3.head = cur         设置反转链表的头结点。

4.cur = curNext

    public ListNode reverseList(ListNode head){if(head == null || head.next == null){return head;}ListNode cur = head.next;head.next = null;while (cur != null){ListNode curNext = cur.next;cur.next = head;head = cur;cur = curNext;}return head;}

图解: 

 LeetCode官方题解:更加简短。循环中第一个节点开始。

    public ListNode reverseList(ListNode head) {ListNode prev = null;ListNode curr = head;while (curr != null) {ListNode next = curr.next;curr.next = prev;prev = curr;curr = next;}return prev;}

 

 

方法二:递归

递归版本稍微复杂一些,其关键在于反向工作。假设链表的其余部分已经被反转,现在应该如何反转它前面的部分?

class Solution {public ListNode reverseList(ListNode head) {if (head == null || head.next == null) {return head;}ListNode newHead = reverseList(head.next);head.next.next = head;head.next = null;return newHead;}
}

详解: 

    /*** 以链表1->2->3->4->5举例* @param head* @return*/public ListNode reverseList(ListNode head) {if (head == null || head.next == null) {/*直到当前节点的下一个节点为空时返回当前节点由于5没有下一个节点了,所以此处返回节点5*/return head;}//递归传入下一个节点,目的是为了到达最后一个节点ListNode newHead = reverseList(head.next);/*第一轮出栈,head为5,head.next为空,返回5第二轮出栈,head为4,head.next为5,执行head.next.next=head也就是5.next=4,把当前节点的子节点的子节点指向当前节点此时链表为1->2->3->4<->5,由于4与5互相指向,所以此处要断开4.next=null此时链表为1->2->3->4<-5返回节点5第三轮出栈,head为3,head.next为4,执行head.next.next=head也就是4.next=3,此时链表为1->2->3<->4<-5,由于3与4互相指向,所以此处要断开3.next=null此时链表为1->2->3<-4<-5返回节点5第四轮出栈,head为2,head.next为3,执行head.next.next=head也就是3.next=2,此时链表为1->2<->3<-4<-5,由于2与3互相指向,所以此处要断开2.next=null此时链表为1->2<-3<-4<-5返回节点5第五轮出栈,head为1,head.next为2,执行head.next.next=head也就是2.next=1,此时链表为1<->2<-3<-4<-5,由于1与2互相指向,所以此处要断开1.next=null此时链表为1<-2<-3<-4<-5返回节点5出栈完成,最终头节点5->4->3->2->1*/head.next.next = head;head.next = null;return newHead;}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com