链表翻转,指定区间
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); } }
相关文章推荐
- 数据结构:单链表(二)之链表节点排序,升序插入数据,删除指定的所有节点,翻转链表操作
- LeetCode-Reverse Linked List II-翻转链表区间-链表操作
- oj2986删除指定区间内的数据(链表操作)
- [LeetCode-92] Reverse Linked List II(反转指定区间链表)
- <LeetCode> 题36:翻转链表2(翻转指定部分)
- 链表指定区间元素的反转
- Java实现单链表翻转实例代码
- 链表相邻元素翻转,如a->b->c->d->e->f-g,翻转后变为:b->a->d->c->f->e->g
- 翻转链表
- 链表的K组翻转问题
- lintcode——翻转链表
- 单链表翻转的三个方法
- 美团网2014校招研发笔试哈尔滨站--链表翻转
- java实现链表指定值得删除,查找第二部分代码
- 算法面试之道:在O(1)的时间内删除单链接链表的指定节点
- 第1章第1节练习题4 有序表删除指定区间值
- [Java GUI] 筛选指定区间内满足条件的数字
- 翻转链表
- 翻转链表 II
- poj2777(指定染色区间统计)