#Traversing linked list?

11 messages · Page 1 of 1 (latest)

long nexus
#

DUMB AS FUCK QUESTION INBOUND

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func mergeTwoLists(list1 *ListNode, list2 *ListNode) *ListNode {
    var tempNode *ListNode
    for list1.Next != nil {
        tempNode = list1
        tempNode.Next = list2
        tempNode.Next.Next = &ListNode{}
        tempNode = tempNode.Next.Next
        
        list1 = list1.Next
        list2 = list2.Next
    }
    return tempNode
}

This is basically a leetcode challenge, that surprised me again.

list1 = list1.Next
list2 = list2.Next

Parts doesnt work and for loop never breaks, what is wrong?

tidal orchid
#

When you're doing tempNode = list1 and then tempNode.Next = list2
You effectively lost all of the nodes in list1

long nexus
#

shit.

#

yeah linked list doesnt work like that.

tidal orchid
#

It's all pointers

#

Plus I think they want you to merge according to the value

#

When I'm doing linked list stuff I find it very useful to draw it on paper

long nexus
#

thank you again

tidal orchid