插入到链表中的位置给出反向输出

时间:2019-03-05 15:52:07

标签: linked-list

在链表中指定位置的插入代码是删除元素而不是插入。请看看。

public void insertAtPos(int data, int pos) {
        Node new_node = new Node(data);
        new_node.next = null;

        Node curr_node = head;

        pos = pos - 1;
        int counter = 0;
        while(curr_node != null) {
            if(counter == pos) {
                Node tmp = curr_node.next;
                curr_node.next = new_node.next;
                new_node.next = tmp.next;
                System.out.println("Element at " + (pos+1) + " inserted!");
                break;
            }
            else {
                new_node = curr_node;
                curr_node = curr_node.next;
                counter++;
            }
        }
    }

0 个答案:

没有答案