Linked Lists

创建一个链表:

NOTE: When you’re discussing a linked list in an interview, make sure to understand whether it is a single linked list or a doubly linked list.
1 class Node {2 Node next = null;3 int data;4 public Node(int d) { data = d; }5 void appendToTail(int d) {6 Node end = new Node(d);7 Node n = this;8 while (n.next != null) { n = n.next; }9 n.next = end;10 }11 }

注意:在面试的时候写链表,一定要先问清楚是写单链表还是双链表!

Deleting a Node from a Singly Linked List

在单链表中删除一个节点

1 Node deleteNode(Node head, int d) {2 Node n = head;3 if (n.data == d) {4 return head.next; /* moved head */5 }6 while (n.next != null) {7 if (n.next.data == d) {8 n.next = n.next.next;9 return head; /* head didn’t change */10 }11 n = n.next;12 }13 }

2 1 Write code to remove duplicates from an unsorted linked list;
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed

2.1从一个未排序的链表中删除重复元素
进阶:如果不能使用额外的空间怎么办?
2.1解答:
如果可以使用哈希表的话,那么检查每一个元素是否重复,然后移除。

如果不能额外使用空间的话,我们就需要两个指针来遍历数组:current用来正常的遍历;runner则用来检查元素是否重复。runner只为一个元素检查一次是否重复,因为每一次runner会删除和元素的所有重复元素。

2.2 Implement an algorithm to find the nth to last element of a singly linked list

2.2 实现算法查找单链表中的倒数第n个元素。
注意:这个问题强烈的暗示递归算法,但是这里才采用一种更巧妙的方法。像这样类似的问题就,一定要多思考看看。能不能用非递归的方法代替递归的方法。
2.2解答:
这里我们假设链表的长度至少为n。
算法描述:
(1) 创建两个指针p1和p2,均指向链表头。
(2) 让p2增加n-1次,使得p2指向从链表头第n个元素(使得p1和p2之间距离为n)
(3) 若p2->next为空,则返回p1;不为空则同时增加p1,p2。(如果p2->next为空,则表示p1所指的元素为倒数第n个,因为p1,p2的距离为n。)
(4) 重复(3)

2.3 Implement an algorithm to delete a node in the middle of a single 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

2.3 实现一个算法,只给你链表中间的一个元素(没有链表头),将其从链表中删除。
例如:
输入:节点 c (原链表为 a->b->c->d->e)
输出:没有任何返回值。但链表变成 a->b->d->e
2.3解答:
本题的解答只是把输入的下一个元素拷贝到输入的这个元素中以完成删除输入的元素。(译者注:原文的代码没有释放下一元素的空间。)
注意:这样的方法并不能删除链表的最后一个元素。这一点需要和你的面试官说清楚。算法有缺陷没有关系,大胆的告诉你的面试官,他们喜欢看到你提出这些。至于怎么解决可以和你的面试官讨论。

2.4 You have two numbers represented by a linked list, where each node contains a single digit The digits are stored in reverse order, such that the 1’s digit is at the head of the list Write a function that adds the two numbers and returns the sum as a linked list  EXAMPLE Input: (3 -> 1 -> 5) + (5 -> 9 -> 2)  Output: 8 -> 0 -> 8

2.4 两个用链表表示的数字,最低位在表头。写一个函数对两个这样的链表求和,采用相同的形式返回结果。
例如: (3 -> 1 -> 5) + (5 -> 9 -> 2)  返回  8 -> 0 -> 8
2.4解答:
本题可以采用递归的方式逐位的做加法。算法流程:

value>10 ? 1 :0 表示是否有进位

原文地址:https://www.cnblogs.com/richardcpp/p/3054724.html