Insert Element in Linked List at Position

To add an element at a specific position in a linked list, you can follow these steps:

  1. Create a new node and assign the element to be inserted as the value of the new node.
  2. Traverse the linked list to find the node before the location where insertion is desired. A pointer can be used to iterate through the linked list until the previous node of the target position is found.
  3. Point the next pointer of the new node to the node pointed to by the next pointer of the previous node at the target position.
  4. Point the next pointer of the previous node at the target location to the new node.

Here is an example code implementation:

public class ListNode {
    int val;
    ListNode next;

    ListNode(int val) {
        this.val = val;
    }
}

public ListNode insert(ListNode head, int position, int value) {
    if (position < 0) {  // 位置小于0时,直接返回原链表
        return head;
    }

    ListNode newNode = new ListNode(value);

    if (position == 0) {  // 插入位置是链表头部
        newNode.next = head;
        head = newNode;
    } else {
        ListNode prev = head;
        int count = 0;

        while (count < position - 1 && prev != null) {  // 找到要插入位置的前一个节点
            prev = prev.next;
            count++;
        }

        if (prev != null) {  // 找到位置,将新节点插入
            newNode.next = prev.next;
            prev.next = newNode;
        }
    }

    return head;
}

This way, you can insert elements at a specified position in the linked list.

bannerAds