这段代码将如何影响链表?

时间:2015-05-12 03:33:40

标签: java linked-list

我有一些代码,我想确保我理解它会如何影响链表。我编码它,它只打印列表的第一个数字,在我的情况下是4.所以说列表是[4,7,1,7,2,0],代码将使列表成为[4]。

Node x = head;

while (x != null) {
  while ((x.next != null) && (x.next.item >= x.item)) {
      x.next = x.next.next;
  }

  x = x.next;
} 

我不确定我是否理解为什么,以及我的代码是否正确。我只被给了这个代码,所以大概我应该在没有编码的情况下理解它。

3 个答案:

答案 0 :(得分:0)

我怀疑:

x.next = x.next.next;

应该是

x = x.next;

答案 1 :(得分:0)

代码流在注释中解释。

Node x = head; //x points to head node.
while (x != null) {
   // continue until x is not null. If x is not null then go to next while.
  while ((x.next != null) && (x.next.item >= x.item)) {
      // continue until next of `x` is also not null and its value is greater than value of some node p (I assume it is previous but not sure as not mentioned)
      x.next = x.next.next; // set next of x to next of next of x (two nodes ahead of x)
      // say x points to 1 and linked list is (nodes and not values) 1 -> 2 -> 3 -> 4 then next of x (pointing to 2) now points to next of next of x (3).
  }
  x = x.next; // x is now pointing to next of x (which is less than x).
} 

如果物品是40 - >; 50 - > 60 - > 20 - > 10最终结果是x指向10.可能是他们希望x指向列表中的最小节点。

答案 2 :(得分:0)

似乎代码正在尝试删除比之前的元素更大的所有元素。它表示如果下一个元素的项大于当前元素的项,则删除下一个元素,但如果下一个元素小于x.item,则将x指针向前移动到下一个元素(保持元素)。你如何检查链接列表后来是什么?结果似乎应该是[4 1 0]

相关问题