面试必考真题-算法篇 牛客网
链表
题目描述
将一个链表m 位置到 n 位置之间的区间反转,要求时间复杂度 O(N),空间复杂度O(1) 。
例如:
给出的链表为1→2→3→4→5→NULL,
返回1→4→3→2→5→NULL。
注意:
给出的 m,n满足以下条件:链表长度1≤m≤n≤链表长度。
题目分析:
将链表分成三段,第一段长度小于m,第二段在m,n之间,第三段在n之后。将第二段进行翻转然后再次拼接这三段链表即可。
下面是Java代码
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
public ListNode reverseBetween (ListNode head, int m, int n) {
// write code here
if(head == null ){
return null;
}
int c = n - m;
if(c == 0){
return head;
}
ListNode pHead = new ListNode(0);
pHead.next = head;
ListNode newHead = pHead;
while(head!=null && m >1){
pHead = pHead.next;
head = head.next;
--m;
}
reverseList(head ,pHead,c);
return newHead.next;
}
private ListNode reverseList(ListNode head,ListNode pre,int n){
ListNode tmp = null;
if(head !=null){
tmp = head.next;
}
ListNode pHead = head;
ListNode node = pre;
while(head.next!=null && n>=1){
tmp = head.next;
head.next = tmp.next;
tmp.next = pre.next;
pre.next = tmp;
--n;
}
return node.next;
}
}