Reverse Linked List II
来源:互联网 发布:蜘蛛软件刷奖软件下载 编辑:程序博客网 时间:2024/06/16 06:14
Q:
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
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
Solution:
Use a fake head to save the head position. Use prev to save the previous node position, because the current node needs to point to the previous node.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode reverseBetween(ListNode head, int m, int n) { if ( m == n) return head; ListNode fakeHead = new ListNode(0); fakeHead.next = head; ListNode before = fakeHead; ListNode cur = head; ListNode start = null; ListNode end = null; int count = 1; while (count < m) { before = before.next; cur = cur.next; count++; } start = cur; ListNode prev = cur; cur = cur.next; while (count < n) { ListNode q = cur.next; cur.next = prev; prev = cur; cur = q; count++; } before.next = prev; start.next = cur; return fakeHead.next; }}
0 0
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Reverse Linked List II
- Leetcode - Insertion Sort List
- java database connection pool 备用
- 对大学专业学习的期望和目标
- halcon与C#混合编程(三)数字识别
- halcon学习笔记——遍历文件夹与文件选择
- Reverse Linked List II
- 人人皆可大数据!SACC教你玩转阿里ODPS
- 基于HALCON的模板匹配方法总结
- deque
- lvds fpga接口干扰解决方法
- 你的理想还在?
- TRIZ系列-创新原理-9~11-预先反作用原理、预处理原理、预先防范原理
- 内存分配子
- 基于MFC对话框的UDP简单聊天程序