将单链表从m到n的结点位置翻转

来源:互联网 发布:淘宝内部优惠券可信吗 编辑:程序博客网 时间:2024/05/21 15:38

题目:反转链表从m-n位置的结点
For example:
Given1->2->3->4->5->NULL, m = 2 and n = 4,
return1->4->3->2->5->NULL.
从第二到第四的结点被反转了。
其中m和n满足条件:
1 ≤ m ≤ n ≤ length of list.

思路:
仍是逆序,仍考虑到用辅助空间stack.
将m-n的结点依次入栈,并标记与入栈结点相邻的前后两个结点pfirst和psecond
(若m==1,pfirst=null,不管n是否为length of list,对psecond的情况无影响。)

代码如下:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
import java.util.*;
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if(head==null)
return null;
if(m==n)
return head;

    Stack<ListNode> stack=new Stack();    //将m-n的结点入栈,将前后相邻的两个结点标记;    int num=1;    ListNode pfirst=null;    ListNode psecond=null;    ListNode p=head;    //特殊情况,m==1时,头结点变更;    if(m==1)            {            pfirst=null;        }    for(;num<=n;num++)        {        //记录pfirst;         if(num<m)            {            if(num==m-1)                {                pfirst=p;            }            p=p.next;              }        else if(num>=m&&num<=n)            {            stack.push(p);            p=p.next;        }    }    //记录psecond,psecond的一般情况仍适用于n=length of list的特殊情况;           psecond=p;    //开始操作链表;    if(pfirst==null)        {        head=stack.pop();        pfirst=head;    }    while(!stack.empty())        {        pfirst.next=stack.pop();        pfirst=pfirst.next;    }        pfirst.next=psecond;    return head;}

}

原创粉丝点击