Cracking the coding interview--Q2.3
2013-07-24 11:34
309 查看
Implement an algorithm to delete a node in the middle of a singly linked list,
given only access to that node.
EXAMPLE
Input: the node c from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a- >b- >d->e
删除链表中的一个节点,但并没有给出链表的头结点,而是只能访问要删除的这个节点。
解答:
将待删除的下一个节点copy到当前节点,然后删除下一个节点。要单独考虑待删除的是链表尾或者链表头的情况。链表头没有特别影响,而如果是链表尾的话,一开始想的是直接将该节点赋值为null,但是测试时发现没有效果。 看书中说如果是链表尾是不能删除的,要向面试官指出这个问题,或者将该节点的数据标记成一个特殊的值表示这个节点是个虚假不用的节点。
given only access to that node.
EXAMPLE
Input: the node c from the linked list a->b->c->d->e
Result: nothing is returned, but the new linked list looks like a- >b- >d->e
删除链表中的一个节点,但并没有给出链表的头结点,而是只能访问要删除的这个节点。
解答:
将待删除的下一个节点copy到当前节点,然后删除下一个节点。要单独考虑待删除的是链表尾或者链表头的情况。链表头没有特别影响,而如果是链表尾的话,一开始想的是直接将该节点赋值为null,但是测试时发现没有效果。 看书中说如果是链表尾是不能删除的,要向面试官指出这个问题,或者将该节点的数据标记成一个特殊的值表示这个节点是个虚假不用的节点。
public class Main { public static void appendToTail(List head, int d) { List end = new List(d); List n = head; while (n.next != null) { n = n.next; } n.next = end; } public static void print(List head) { List n = head; System.out.print("{"); while (n != null) { if (n.next != null) System.out.print(n.data + ", "); else System.out.println(n.data + "}"); n = n.next; } } public static boolean revomeNode(List node) { if (node == null || node.next == null) { return false; } else { node.data = node.next.data; node.next = node.next.next; return true; } } public static void main(String args[]) { List list = new List(0); appendToTail(list, 1); appendToTail(list, 2); appendToTail(list, 3); appendToTail(list, 4); appendToTail(list, 5); appendToTail(list, 6); appendToTail(list, 7); appendToTail(list, 8); appendToTail(list, 9); print(list); List node = list; for(int i = 0; i < 9; i++) node = node.next; System.out.println(revomeNode(node)); print(list); } } class List { int data; List next; public List(int d) { this.data = d; this.next = null; } }
相关文章推荐
- Cracking the coding interview--Q2.3
- Cracking the coding interview--Q2.3
- Cracking the coding interview--Q2.3
- Cracking the coding interview--Q2.3
- Cracking the coding interview--Q1.5
- Cracking the coding interview--Q9.6
- Cracking the coding interview--Q3.1
- Cracking the coding interview--Q4.5
- Cracking the Coding Interview 智力题
- Cracking the coding interview--Q9
- 渣基础:比照Hawstein学Cracking the coding interview(1)
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目8
- Cracking the coding interview--Q12.5
- 渣基础:比照Hawstein学Cracking the coding interview(2)
- 《Cracking the Coding Interview》——第5章:位操作——题目1
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目6
- Cracking the coding interview--14.1-14.6
- Cracking the Coding Interview
- Cracking the coding interview--Q2.2
- Cracking the coding interview Q1.2