138. Copy List with Random Pointer
这道题答案在网上找的。。。有两种解题方法,一种是用hashtable。另外一种是先复制List中的每一个node再加到node后面,然后将node的random reference复制给新加的node,再将新加的node都分出来,最后进行输出。。。
public class Solution {
public RandomListNode copyRandomList(RandomListNode head) {if(head == null)
return head;
RandomListNode node = head;
while(node != null){
RandomListNode newNode = new RandomListNode(node.label);
newNode.next = node.next;
node.next = newNode;
node = newNode.next;
}
node = head;
while(node != null){
if(node.random != null)
node.next.random = node.random.next;
node = node.next.next;
}
RandomListNode newHead = head.next;
node = head;
while(node != null){
RandomListNode newNode = node.next;
node.next = newNode.next;
if(newNode.next!=null)
newNode.next = newNode.next.next;
node = node.next;
}
return newHead;
}
}
109. Convert Sorted List to Binary Search Tree
这个数据结构课做过,用递归解决。先递归左边,再递归右边
public class Solution {
private ListNode curr;
public TreeNode sortedListToBST(ListNode head) {
if (head == null) {
return null;
}
curr = head;
int length = getLength(head);
return sortedListToBST(length);
}
private int getLength(ListNode head) {
int len = 0;
ListNode curr1 = head;
while (curr1 != null) {
len++;
curr1 = curr1.next;
}
return len;
}
private TreeNode sortedListToBST(int size) {
if (size <= 0) {
return null;
}
TreeNode left = sortedListToBST(size / 2);
TreeNode root = new TreeNode(curr.val);
curr = curr.next;
TreeNode right = sortedListToBST(size - 1 - size / 2);
root.left = left;
root.right = right;
return root;
}
}
92. Reverse Linked List II
这个就是用for-loop来解决,麻烦的是变量比较多容易错
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
if (m >= n || head == null) {
return head;
}
ListNode dummy = new ListNode(0);
dummy.next = head;
head = dummy;
for (int i = 1; i < m; i++) {
if (head == null) {
return null;
}
head = head.next;
}
ListNode premNode = head;
ListNode mNode = head.next;
ListNode nNode = mNode, postnNode = mNode.next;
for (int i = m; i < n; i++) {
if (postnNode == null) {
return null;
}
ListNode temp = postnNode.next;
postnNode.next = nNode;
nNode = postnNode;
postnNode = temp;
}
mNode.next = postnNode;
premNode.next = nNode;
return dummy.next;
}
}
本文解析了三道经典的链表与树转换编程题:链表带随机指针的复制、有序链表转二叉搜索树及链表区间反转。提供了详细的算法实现思路与代码示例。
165

被折叠的 条评论
为什么被折叠?



