reverse list between m and n

来源:互联网 发布:兰州网络教育学生平台 编辑:程序博客网 时间:2024/06/05 18:03

题目描述

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:
Given1->2->3->4->5->NULL, m = 2 and n = 4,

return1->4->3->2->5->NULL.

Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
我的算法:

public class Solution {    public ListNode reverseBetween(ListNode head, int m, int n) {        if(head==null||head.next==null||m==n)return head;        ListNode dummy=new ListNode(0);        dummy.next=head;        ListNode pre=dummy,tail,tmp;        while(m-1>0){            pre=pre.next;            n--;            m--;        }        tail=pre;        while(n>0){            tail=tail.next;            n--;        }        tmp=pre.next;        pre.next=tail;        pre=tmp;        while(pre!=tail){            tmp=pre;            pre=pre.next;            tmp.next=tail.next;            tail.next=tmp;        }        return dummy.next;    }}
0 0
原创粉丝点击