当前位置:   article > 正文

LeetCode 206

leetcode 206

题目描述:反转链表

 给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

提示:

  • 链表中节点的数目范围是 [0, 5000]
  • -5000 <= Node.val <= 5000

例如:

输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]

 方法一:边遍历原链表,边创建一个新链表(题目中没有对空间复杂度的要求),头插法插入即可。

addFirst(5->4->3->2->1);

如下图所示:

代码实现:

  1. package LeetCode;
  2. public class Num206 {
  3. //头插法
  4. public ListNode reverseList(ListNode head) {
  5. if (head == null || head.next == null){
  6. //如果原链表为空,返回head也为空;如果原链表的后继为空,返回head就是head节点
  7. return head;
  8. }
  9. //新链表的虚拟头节点
  10. ListNode dummyHead = new ListNode(5001);
  11. //边遍历原链表,边头插新链表
  12. while(head != null){
  13. //创建新节点使得新节点的值等于原链表头节点的值
  14. ListNode node = new ListNode(head.val);
  15. node.next = dummyHead.next;
  16. dummyHead.next = node;
  17. head = head.next;
  18. }
  19. //返回新链表的头节点,即虚拟节点的后继
  20. return dummyHead.next;
  21. }
  22. }

方法二:原地移动法,当题目要求空间复杂度为O(1)时,只能改变原链表的指向。

注意:回文链表只是原链表的next不再指向后继转而指向前驱。

我们可以引入两个引用:

  • cur->表示当前需要处理的节点
  • prev->表示当前节点的前驱,cur.next = prev;
  • next->next = cur.next,用来暂存下一个需要处理的节点。

如图所示: 

 

  1. //原地移动法
  2. public ListNode reverseList(ListNode head){
  3. if (head ==null || head.next == null){
  4. return head;
  5. }
  6. ListNode prev = null;
  7. //cur表示当前需要反转的节点
  8. ListNode cur = head;
  9. while(cur != null){
  10. ListNode next = cur.next;
  11. cur.next = prev;
  12. prev = cur;
  13. cur = next;
  14. }
  15. return prev;
  16. }

方法三:传入一个以head为头节点的链表,reverseList()方法就可以将次链表反转并且返回反转后链表的头节点。

 

 代码实现:

  1. //递归法
  2. public ListNode reverseList(ListNode head){
  3. //1、判空
  4. if (head ==null || head.next == null){
  5. return head;
  6. }
  7. ListNode sec = head.next;
  8. //2、反转第二个节点之后的子链表
  9. ListNode newHead = reverseList(head.next);
  10. //3、处理head与sec关系
  11. sec.next = head;
  12. head.next = null;
  13. return newHead;
  14. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/209873
推荐阅读
相关标签
  

闽ICP备14008679号