您的位置:首页 > 其它

链表翻转,指定区间

2013-06-28 10:07 239 查看
/**
* 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.

难点在于,只能一次遍历,如何检验m,n的有效性。
*
*/
public class RevertList2 {

public static Element reverse(Element head, int m, int n) throws Exception{
assert(true);//size大于1, m小于n大于0
Element newHead = head;
Element h1 = null;
Element h2 = null;
Element t1 = null;
Element t2 = null;
Element pre = null;
Element current = head;
Element next = current.next;
int i = 1;
while(true){
if(next == null){
throw new Exception();
}
if(i == m){
h1 = pre;
h2 = current;
next = current.next;
break;
}
pre = current;
current = next;
next = next.next;
i++;
}
while(true){
if(current == null){
throw new Exception();
}
if(i == n){
t1 = current;
t2 = next;
break;
}
if(next == null){
throw new Exception();
}
Element e = next.next;
next.next = current;
current = next;
next = e;
i++;
}
if(h1 == null){
newHead = t1;
}else{
h1.next = t1;
}
h2.next = t2;
return newHead;
}
/**
* @param args
*/
public static void main(String[] args) {
Element head = new Element(1);
Element a1 = new Element(2);
Element a2 = new Element(3);
Element a3 = new Element(4);
Element a4 = new Element(5);
Element a5 = new Element(6);
Element a6 = new Element(7);
Element a7 = new Element(8);
Element a8 = new Element(9);
head.next = a1;
a1.next = a2;
a2.next = a3;
a3.next = a4;
a4.next = a5;
a5.next = a6;
a6.next = a7;
a7.next = a8;

Tools.printList(head);
Element h = null;;
try {
h = RevertList2.reverse(head, 8, 9);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Tools.printList(h);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: