在面试过程中,数据结构和算法基本上算是研发类岗位必考的部分,而链表基本上又是数据结构中相对容易掌握、而且容易出题的部分,因此我们先整理一下链表部分的经典题目。
(声明:以下所有程序都是用java编写)
首先,我们来定义一个链表的数据结构,如下:
View Code
1 public class Link {
2 private int value;
3 private Link next;
4 public void set_Value(int m_Value) {
5 this.value = m_Value;
6 }
7 public int get_Value() {
8 return value;
9 }
10 public void set_Next(Link m_Next) {
11 this.next = m_Next;
12 }
13 public Link get_Next() {
14 return next;
15 }
16 }
有了这个数据结构后,我们需要一个方法来生成和输出链表,其中链表中每个元素的值采用的是随机数。
生成链表的代码如下:
View Code
1 public static Link init(int count, int maxValue)
2 {
3 Link list = new Link();
4 Link temp = list;
5 Random r = new Random();
6 temp.set_Value(Integer.MIN_VALUE);
7 for (int i = 0; i < count; i++)
8 {
9 Link node = new Link();
10 node.set_Value(r.nextInt(maxValue));
11 temp.set_Next(node);
12 temp=node;
13 }
14 temp.set_Next(null);
15 return list;
16 }
17
18 public static Link init(int count)
19 {
20 return init(count, Integer.MAX_VALUE);
21 }
对于链表的头结点,我们是不存储任何信息的,因此将其值设置为Integer.MIN_VALUE。我们重载了生成链表的方法。
下面是打印链表信息的方法:
View Code
1 public static void printList(Link list)
2 {
3 if (list == null || list.get_Next() == null)
4 {
5 System.out.println("The list is null or empty.");
6 return;
7 }
8 Link temp = list.get_Next();
9 StringBuffer sb = new StringBuffer();
10 while(temp != null)
11 {
12 sb.append(temp.get_Value() + "->");
13 temp=temp.get_Next();
14 }
15 System.out.println(sb.substring(0, sb.length() - 2));
16 }
好了,有了以上这些基础的方法, 我们就可以深入探讨链表相关的面试题了。
- 链表反转
思路:有两种方法可以实现链表反转,第一种是直接循环每个元素,修改它的Next属性;另一种是采取递归的方式。
首先来看直接循环的方式:
View Code
1 public static Link Reverve(Link list)
2 {
3 if (list == null || list.get_Next() == null || list.get_Next().get_Next() == null)
4 {
5 System.out.println("list is null or just contains 1 element, so do not need to reverve.");
6 return list;
7 }
8 Link current = list.get_Next();
9 Link next = current.get_Next();
10 current.set_Next(null);
11 while(next != null)
12 {
13 Link temp = next.get_Next();
14 next.set_Next(current);
15 current = next;
16 next = temp;
17 }
18 list.set_Next(current);
19
20 return list;
21 }
然后是递归方式:
View Code
1 public static Link RecursiveReverse(Link list)
2 {