如何在链表中的给定位置插入项目? [英] How to insert an item at a given position in a linked list?

查看:18
本文介绍了如何在链表中的给定位置插入项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是您添加项目的方式:

This how you would add an item:

public void insert (Object item)
{
    Link add = new Link();
    add.data = item;
    add.next = head;
    _head = add;
    ++_listsize;
 }

但是如何在给定位置添加项目.到目前为止,这是我得到的:

But how do you add an item at a given position. So far this is what I got:

public void insert (Object item, int pos)
{
    Link add = new Link();
    int ix = pos - 1;
    add.next = _head;
    for (int i = _listsize - 1; i >= ix; --i)
        add = add.next;
    add.data = item;
    _head = add;
   ++_listsize;

 }

如果它是连续的,这将正确插入项目,但假设我得到了一个位于中间的位置,它将插入该项目但它会完全切断(或删除其余部分).例如:

This will insert the item correctly if it is sequential, but let say I am given a position which is in the middle, what it will do it will insert the item but it will completely cut off (or delete the rest). For example:

在 1 处插入:一个

在 2 处插入:乙一个

insert at 2: b a

在 3 处插入:C乙一个

insert at 3: c b a

在 2 处插入:d一个

insert at 2: d a

推荐答案

您似乎没有将新的 Link 正确插入到列表中.当你这样做时,你需要找到给定位置的 Link 以及前一个位置的 Link.那么只有你可以设置previous.next = addadd.next = position.

It seems you have not correctly inserted the new Link into the list. When you do that, you need to find the Link at the given position as well as the Link at the previous position. Then only you can set the previous.next = add and add.next = position.

以下是完成任务的更新方法.

Below is the updated method that does the task.

public void insert (Object item)
{
    Link add = new Link();
    add.data = item;
    add.next = _head;
    _head = add;
    ++_listsize;
 }

public void insert (Object item, int pos)
{
    Link add = new Link();
    add.data = item;

    int ix = pos - 1;
    add.next = _head;

    Link previous = _head;

    for (int i = _listsize - 1; i > ix; --i) {
        previous = previous.next;
    }

    Link position = previous.next;

    previous.next = add;
    add.next = position;
    ++_listsize;
}

这篇关于如何在链表中的给定位置插入项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆