简体   繁体   English

在给定位置搜索节点双链表

[英]search for a node at a given position doubly linked list

I am trying to search for a node based on the position of the node in a doubly linked list. 我正在尝试根据双向链接列表中节点的位置搜索节点。 For example, if the list contains 1,2,3,4,5 and I want to get position 3, it will return positions data, which is 3. I was able to get the first and second position, but when I try any other position after the second, it only returns the second position. 例如,如果列表包含1,2,3,4,5并且我想获得位置3,它将返回位置数据3。我能够获得第一个和第二个位置,但是当我尝试任何一个第二个位置之后的其他位置,则仅返回第二个位置。 I am not sure what is wrong. 我不确定是怎么了。 Here is my code so far: 到目前为止,这是我的代码:

Insert Method 插入方式

public void insertAtStart(String data)
    {
        Node ptr = new Node(data);
        if(head == null)
        {
            head = ptr;
            tail = head;
        }
        else
        {
            head.prev = ptr;
            ptr.next = head;
            head = ptr;
        }
        size++;
    }

Search Method 搜索方式

public Node searchAt(int pos)
    {
        Node found = head;

        if(isEmpty())
        {
            System.out.println("List is empty");
            return null;
        }

        if(pos == 1)
            return found;

        for(int i = 2; i <= size; i++)
        {
            if(i == pos)
            {
                found = head.next;
            }
        }
        return found;
    }

Test: 测试:

        doc.insertAtStart("1");
        doc.insertAtStart("2");
        doc.insertAtStart("3");
        doc.insertAtStart("4");
        doc.insertAtStart("5");

        doc.printReverse();
        Node newNode = doc.searchAt(4);
        System.out.println("Node" + newNode.data);

output: 输出:

1: 1
2: 2
3: 3
4: 4
5: 5
Node: 2

The problem is at this line: 问题在这一行:

found = head.next;

You always return the second element (and the first one works thanks to the first branch of your if statement). 您总是返回第二个元素(第一个元素的工作要归功于if语句的第一个分支)。

You should instead run through the list and get the correct element. 您应该浏览列表并获取正确的元素。

Tweak the for loop a bit: 稍微调整for循环:

  • Move one position in list every iteration 每次迭代在列表中移动一个位置
  • Break loop when position is reached. 到达位置时中断循环。

     for(int i = 2; i <= size; i++) { found = head.next; if(i == pos) { break; } } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM