您的位置:首页 > 其它

Reverse Linked List | & ||

2016-07-03 07:32 232 查看

Reverse Linked List I

Reverse a linked list.

Example

For linked list
1->2->3
, the reversed linked list is
3->2->1


分析:

典型的3 pointers 问题。

/**
* Definition for ListNode.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int val) {
*         this.val = val;
*         this.next = null;
*     }
* }
*/
public class Solution {
/**
* @param head: The head of linked list.
* @return: The new head of reversed linked list.
*/
public ListNode reverse(ListNode head) {
if (head == null) return head;
ListNode prev = null;
ListNode cur = head;
ListNode next = null;
while (cur != null) {
next = cur.next;
cur.next = prev;
prev = cur;
cur = next;
}
return prev;
}
}


Reverse Linked List II

Reverse a linked list from position m to n.

Note: Given m, n satisfy the following condition: 1 ≤ m ≤ n ≤ length of list.

Example

Given
1->2->3->4->5->NULL
, m =
2
and n =
4
, return
1->4->3->2->5->NULL
.

分析:

我们需要把list分成三段。首先得到第一段的最后一个node,然后reverse中间部分。最后把三个部分链接起来。

/**
* Definition for ListNode
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
/**
* @param ListNode head is the head of the linked list
* @oaram m and n
* @return: The head of the reversed ListNode
*/
public ListNode reverseBetween(ListNode head, int m , int n) {
if (m == n) return head;
ListNode tempHead = new ListNode(1);
tempHead.next = head;

// reach the end of the first part
ListNode partEnd = tempHead;
for(int k = 1; k < m; k++) {
partEnd = partEnd.next;
}
// save it later to connect to the last part.
ListNode secondPartTail = partEnd.next;

// reverse the middle part
ListNode prev = null;
ListNode current = partEnd.next;
ListNode next = null;

for (int p = 1; p <= n - m + 1; p++) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
// connect three parts
partEnd.next = prev;
secondPartTail.next = current;

return tempHead.next;
}
}


转载请注明出处:cnblogs.com/beiyeqingteng/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: