2018-08-15 LeetCode旋转链表反转链表

反转链表原型

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode pre = null;
        ListNode next = null;
        while(head!=null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
        //方法二 递归
        // if(head==null || head.next==null){
        //     return head;
        // }
        // ListNode h = reverseList(head.next);
        // head.next.next = head;
        // head.next = null;
        // return h;
    }
}

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
遍历链表统计链表长度的同时记录尾节点的位置

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head==null||head.next==null||k==0)
            return head;
        int n=0;
        ListNode cur = head, tail=head;
        while(cur != null){
            n++;
            tail = cur;
            cur = cur.next;
        }
        k = n - k % n;
        if(k == n) return head;
        cur = head;
        while(--k > 0){
            cur = cur.next;
        }
        ListNode newHead = cur.next;
        cur.next = null;
        tail.next = head;
        return newHead;
    }
}

反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode first = dummy;        
        for (int i = 0; i < m-1; i++){
            first = first.next;
        }
        ListNode cur = first.next;        
        for (int i = 0; i<n-m; i++){
            ListNode node = cur.next;
            cur.next = node.next;
            node.next = first.next;
            first.next = node;          
        }        
        return dummy.next;        
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 搞懂单链表常见面试题 Hello 继上次的 搞懂基本排序算法,这个一星期,我总结了,我所学习和思考的单链表基础知识...
    醒着的码者阅读 4,608评论 1 45
  • (一)LeetCode206.反转链表 题目描述: 反转一个单链表。 代码实现 (二)LeetCode160. 相...
    Jarily阅读 1,417评论 0 5
  • 1. 找出数组中重复的数字 题目:在一个长度为n的数组里的所有数字都在0到n-1的范围内。数组中某些数字是重复的,...
    BookThief阅读 1,808评论 0 2
  • 庙堂高高空无痕, 新朝既定草木深。 最是皇家无情事, 一朝天子一朝臣。
    曾国藩小姐姐阅读 643评论 1 16
  • 净烟器广告 文/白乌鸦 净烟器广告照片 第一张 是抽烟20年肺癌死者的肺 黑乎乎的 看着恐怖 第二张 是使用净烟器...
    南倚闲坐阅读 163评论 0 0