combine items of list

2019-09-21 14:52发布

Hi I have a list with lets say these items {30 50 5 60 90 5 80} what I want to do is for example combine the 3rd and 4th element together and have {30 50 65 90 5 80}

Could you tell me how would I do that? I am using the java linked list class.

5条回答
手持菜刀,她持情操
2楼-- · 2019-09-21 14:59
public class Main {
    public static void main(String[] args) {
        List<Integer> list = new LinkedList<>();
        list.add(30);
        list.add(50);
        list.add(5);
        list.add(60);
        list.add(90);
        list.add(5);
        list.add(80);
        System.out.println(list);
        combine(list, 2, 3);
        System.out.println(list);
    }
    public static void combine(List<Integer> list, int indexA, int indexB) {
        Integer a = list.get(indexA);
        Integer b = list.get(indexB);
        list.remove(indexB); // [30, 50, 5, 90, 5, 80]
        list.add(indexA, a + b); // [30, 50, 65, 5, 90, 5, 80]
        list.remove(indexB); // [30, 50, 65, 90, 5, 80]
    }
}

The output is:

[30, 50, 5, 60, 90, 5, 80]
[30, 50, 65, 90, 5, 80]

You need check nulls values for avoid NullPointerException

查看更多
SAY GOODBYE
3楼-- · 2019-09-21 15:04

Add the two values in the current links, remove the two links and add a new one in their place. The API for that is at: http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html Use the remove and add methods.

查看更多
孤傲高冷的网名
4楼-- · 2019-09-21 15:10

Linked list does not provide the methods for performing operations over the list, it only manages the list. The only way to do this for you would be to retrieve the elements from the said locations and add them up and then remove the said elements from the list and then insert the new item using index.

查看更多
狗以群分
5楼-- · 2019-09-21 15:15

I'd loop through your linked list (start at the head node). I'm guessing there is a nextNode property on each LinkedList object that allows your iterator to work. When you get to index 2 (with value 5), find the nextnode of index 2 (with value 60), and add that value to index 2 (with value 5 making it 65). Then find the nextNode of index 3 (with value 60) which points to the node with value 90 (call this newNextNode) and reset the nextNode property of index 2 (with value 5) to that node.

查看更多
一夜七次
6楼-- · 2019-09-21 15:20

Read the API documentation for LinkedList. There isn't a "combine" method, but there is a method to remove the element at a given index, and an method to insert an element anywhere in the list.

http://docs.oracle.com/javase/7/docs/api/java/util/LinkedList.html

查看更多
登录 后发表回答