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

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

问题描述

这是您添加项目的方式:

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: b 一个

插入3: C b 一个

insert at 3: c b a

插入2: d 一个

推荐答案

似乎您没有正确地将新的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天全站免登陆