您的位置:首页 > 产品设计 > UI/UE

amazon oa2 - insert a value into a cycled linked list

2016-01-18 13:09 417 查看
遍历,一共有三种情况,

1. pre <= x <= current

2. 遍历到了head时,x>tail 或者 x<=head (不会等于tail)

3. 遍历回aNode或同值的Node,此时直接插到此Node的前面

public void insert(Node aNode, int x) {
  ListNode last = aNode;
  ListNode current = aNode.next;
  while (current.val != aNode.val) {
    if(last.val<=x && x<=current.val) {
      insertbtw(last,current,x);
      return;
    }
    else {
      if (last.val>current.val && (last.val<x || x<=current.val)) {
        insertbtw(last,current,x);
        return;
      }
    }
    last = current;
    current = current.next;
  }
  if(!inserted) {
    insertbtw(last,current,x);
  }
  return;
}

public void insertbtw(ListNode last, ListNode current, int x) {
  ListNode temp = new ListNode(x);
  last.next = temp;
  temp.next = current;

  return;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: