leetcode:反转链表--反转链子表

题目:反转链表

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

示例:

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

提示:

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

-5000 <= Node.val <= 5000

代码:

public ListNode reverseList(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode last=head;
        ListNode node=head.next;
        ListNode temp;//辅助交换
        while(node!=null){
            temp=node;
            node=node.next;
            temp.next=head;
            head=temp;
        }
        last.next=null;
        return head;
    }

结果:

题目2:

给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。

示例:

示例 1:

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

示例 2:

输入:head = [5], left = 1, right = 1
输出:[5]

提示:

链表中节点数目为 n

1 <= n <= 500

-500 <= Node.val <= 500

1 <= left <= right <= n

思路:

将反转部分从原链表上切割下来成为单独链表,就和的一个一样了将反转获得的链表在接到原来的地方就行

代码:

public ListNode reverseBetween(ListNode head, int left, int right) {
    if (head.next == null || left == right){
        return head;
    }
    ListNode xuni = new ListNode(-1); //虚拟头
    xuni.next = head;

    ListNode l = xuni; // 初始化指向第一部分末尾的指针
    ListNode r = xuni; // 初始化指向待反转部分末尾的指针

    while (left > 1) {
        l = l.next;
        --left;
    }

    while (right > 0) {
        r = r.next;
        --right;
    }
    ListNode newhead=l.next;
    l.next=null;
    ListNode restNode = r.next; //后半部分
    r.next = null; // 断开

    ListNode rnewhead = reverseList(newhead);
    l.next = rnewhead;

    ListNode cur = xuni.next; // 初始化遍历指针为头结点
    while (cur.next != null) { // 将遍历指针移动到原链表的末尾节点
        cur = cur.next;
    }
    cur.next = restNode; // 连接剩余部分
    return xuni.next; // 返回反转后的链表头结点
}

    public ListNode reverseList(ListNode head) {
        if (head == null) {
            return head;
        }
        ListNode last = head;
        ListNode node = head.next;
        ListNode temp;//辅助交换
        while (node != null) {
            temp = node;
            node = node.next;
            temp.next = head;
            head = temp;
        }
        last.next = null;
        return head;
    }

结果:

相关推荐

  1. leetcode-

    2024-01-25 16:10:01       38 阅读
  2. leetcode206.

    2024-01-25 16:10:01       37 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-25 16:10:01       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-25 16:10:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-25 16:10:01       18 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-25 16:10:01       20 阅读

热门阅读

  1. 数据结构——链式栈

    2024-01-25 16:10:01       36 阅读
  2. [力扣 Hot100]Day13 最大子数组和

    2024-01-25 16:10:01       40 阅读
  3. redis 分布式锁的原理

    2024-01-25 16:10:01       35 阅读
  4. uniapp使用uQRCode插件生成二维码的简单使用

    2024-01-25 16:10:01       38 阅读
  5. K8S的安全机制

    2024-01-25 16:10:01       37 阅读
  6. Shell条件判断与流控匹配

    2024-01-25 16:10:01       32 阅读