LeetCode-92. Reverse Linked List II

来源:互联网 发布:淘宝退货运费多少钱 编辑:程序博客网 时间:2024/06/05 20:32

题目描述

Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

解题思路

将指定位置的链表元素翻转,有点类似于LeetCode-25主要还是从递归和遍历两个方面求解

代码

遍历解决

class Solution {    public ListNode reverseBetween(ListNode head, int m, int n) {        if(head == null || m>=n)            return head;        ListNode result = new ListNode(0);        result.next = head;        ListNode pre = result;        ListNode after = head.next;        int position =1;        while(position<n && head != null && after!=null){            if(position == m){                while(position<n && head!=null && after !=null){                    ListNode tmp = after.next;//一开始这个地方用tmp=head.next.next,因为期望head.next=after,但是这个条件仅是在本循环体的第一次循环中满足,后面head.next指向了前面的结点                   after.next = head;                    head = after;                    after = tmp;                    position++;                }                pre.next.next = after;                pre.next = head;                break;            }else{                pre = head;                head = after;                after = after.next;                position++;            }        }        return result.next;    }}

递归解决

class Solution {    ListNode tail = null;//使用tail变量保存位置n后面的节点    public ListNode reverseBetween(ListNode head, int m, int n) {        if(head == null || m>=n)            return head;        ListNode result = new ListNode(0);        result.next = head;        return reverseCore(result,m,n,0).next;    }    private ListNode reverseCore(ListNode head,int m,int n,int position){        if(position == n){//最后一个需要翻转的链表            tail = head.next;            return head;        }        ListNode reHead = reverseCore(head.next,m,n,position+1);        if(position >= m){//m-n范围内的元素,执行翻转逻辑            head.next.next = head;            return reHead;        }else if(position == m-1){//m-1位置的元素,需要将tail安放当合适的位置            head.next.next = tail;            head.next = reHead;        }        return head;    }}
原创粉丝点击