0

好的,解决方案可能很简单,但我目前不明白。

代码:

ListElem<T> first;
int size = 0;
public void add(T value) {
  if (value == null)
    return;
  ListElem<T> elem = new ListElem<T>(value);
  elem.next = first;
  first = elem;
  size++;
}

这究竟是如何在单链链表的开头添加一个元素的?我用给定的值创建了一个新元素。

接下来的 2 行会发生什么?我了解在列表中插入元素的过程,但我无法将其与此代码相关联。

究竟什么是第一?头部?

4

2 回答 2

3

Before adding the stack looks like this :

first -> next -> next -> ... -> end;

You create the elem.

Then you said "The next elem of elem is the first elem".

elem.next = first; so you have

elem -> first;

Finally you set the first elem to elem. So the stack looks like this :

elem -> first -> next -> ... -> end;

and first id now the elem so basically you return to the first state :

first -> next -> next -> ... -> end; (first is now the new elem you just added)

This schema may be helpful :

enter image description here

于 2013-05-14T21:01:32.743 回答
0
elem.next = first;

means previous first element should be next to your new element

first = elem;

means your new element becomes first

于 2013-05-14T21:02:45.633 回答