算法

反转链表

2020-10-12  本文已影响0人  小鱼嘻嘻

问题1

如何把一个链表反转过来,例如1->2->3->4 反转为4->3->2->1 ?

原理

可以重写定义一个头结点,然后采用头插的方式把老的链表插入到新的链表里,头插法如何实现可以参考:头插法

代码

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode newHead = new ListNode(-1);
        ListNode run = newHead;
        while (head!=null){
            ListNode cur = head;
            head = head.next;
            cur.next = run.next;
            run.next = cur;
        }
        return newHead.next;
    }
}

注意事项

在做头插的时候要注意节点移动的时候,ListNode cur = head; head = head.next; 不要让老的链表断开。

问题2

如何旋转链表的m->n中间节点旋转过来,例如1->2->3->4 反转2到3为 1->3->2->4

原理

代码

class Solution {
    public ListNode reverseBetween(ListNode head, int m, int n) {
        if(head==null){
            return head;
        }
        // find first
        ListNode newHead = new ListNode(-1);
        ListNode run = newHead;
        for(int i=1;i<m;i++){
            run.next = head;
            head = head.next;
            run = run.next;
        }
            
        // find second
        ListNode dump = head;
        ListNode reverseHead = new ListNode(-1);
        ListNode reverseRun = reverseHead;
        for(int i=m;i<=n;i++){
            ListNode cur = head;
            head = head.next;
            cur.next = reverseRun.next;
            reverseRun.next = cur;
        }
        //find third
        run.next = reverseHead.next;
        dump.next = head;

        return newHead.next;
    }
}

注意事项

问题3

把一个长度为n的链表,按照长度为m的规则反转,注意的是n>=m>0

原理

代码

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null||k<=0){
            return head;
        }
        ListNode newHead = new ListNode(-1);
        ListNode run = newHead;
        ListNode dump = null;
        int count = k;
        Stack<ListNode> stack = new Stack<>();
        while(true){
            dump = head;
            while(head!=null&&count>0){
                stack.add(head);
                head = head.next;
                count--;
            }

            if(count>0){
                break;
            }

            while(!stack.isEmpty()){
                ListNode cur = stack.pop();
                run.next = cur;
                run = run.next;
            }
            count = k;
        }
        run.next = dump;
        return newHead.next;
    }
    
}

注意事项

上一篇 下一篇

猜你喜欢

热点阅读