在链表的第n个位置插入一个节点

时间:2018-03-17 06:49:08

标签: python linked-list

这是一个黑客问题"在链接列表的第n个位置插入一个节点"。根据问题的描述,我们应该在位置1插入10。

3 > 5 > 4 > 2 > Null是现有的链接列表,我们必须在索引1处插入10。输出应该如下3 >10 > 5 > 4 > 2 > Null。这是我的代码:

def InsertNth(head, data, position):
    temp = Node(data)
    if (head == None):
        head = temp  #if head is Null then new node is the head
        temp.next = None
        #return head
    else:
        current = head
        i = 0
        while(i < position - 1):
        #for i in range(position-1):
            current = current.next 
            i = i +1
        next_node = current.next  #keep the address to the next element
        current.next = temp .     
        temp.next = next_node
    return head

我使用此代码获得的输出是2> 10 > 5 > 4 > 2 > Null,这是错误的。我尝试了很多修复,但代码看起来很好。任何人都可以用一些解释指出我的错误吗?

2 个答案:

答案 0 :(得分:0)

以下是我的表现。您需要在while中进行两次检查 - 一次检查以确保i不会越过position,另一种是确保您不会脱离链接列表的末尾(可能当position大于您的链接列表的大小时。)

如果您要在position插入,i应停在position - 1。然后,将cur.next设置为temp,将temp.next设置为cur.next的旧值。您不需要代理对象来交换指针(next_node,在您的代码中是不必要的)。

def insert(head, data, position):
    temp = Node(data)
    # handle all the base cases - empty list or position == 0
    if not head or position == 0:
        temp.next = head
        head = temp
    else:       
        cur = head
        i = 0
        while i < position - 1 and cur.next is not None:   
            cur = cur.next
            i += 1
        temp.next = cur.next
        cur.next = temp

    return head  

enter image description here

请遵循PEP8标准,仅用于标识符名称的蛇案例。

可以在https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem 找到挑战。

答案 1 :(得分:0)

class Node:
    def __init__(self, data):
        self.data = data;
        self.next = None;

class LinkdList:
    def __init__(self):
        self.head = None;

    def insert(self, x, position):
        temp = Node(x);
        if position == 0 or self.head == None:
            temp.next = self.head;
            self.head = temp;
            return
        cur = self.head;
        for i in range(0, position-1):
            cur = cur.next;
            if cur.next == None:
                break;
        temp.next = cur.next;
        cur.next = temp;



    def printList(self):
        temp = self.head;
        while temp:
            print(temp.data, end= " ")
            temp = temp.next

l = LinkdList();