JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

LeetCode :206.反转链表 反转链表golang

wys521 2024-11-02 14:58:39 精选教程 30 ℃ 0 评论

题目:

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


示例 1:

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

输出:[5,4,3,2,1]

示例 2:

输入:head = [1,2]

输出:[2,1]

示例 3:

输入:head = []

输出:[]


提示:

链表中节点的数目范围是 [0, 5000]

-5000 <= Node.val <= 5000

来源:力扣(LeetCode)

链接:https://leetcode-cn.com/problems/reverse-linked-list

著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题:

1.定义一个新的链表,遍历需反转的链表,将头节点插入新链表,实现反转,这种解法比较简单容易理解,但是空间复杂度比较高,每次都生成了新的节点;

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

        ListNode curr = new ListNode();
        while (head != null) {
            //生成新节点,插入链表头部
            curr.next = new ListNode(head.val,curr.next);
            head= head.next;
        }
        return curr.next;
        
    }

2.利用指针,移动指针,实现反转;

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

       ListNode cur = head;
       ListNode temp = null;

       while(head.next != null){
           temp= head.next.next;
           head.next.next = cur;
           cur = head.next;
           head.next = temp;
       }
       return cur;
        
    }

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表