Published on

Single linked list trick collection

Authors

Reverse

When we need to process data from tail to head, so we need to read reverse data flow backward because we cannot going back directly using single linked list.


_16
// Singly-linked lists are already defined with this interface:
_16
// type ListNode struct {
_16
// Value interface{}
_16
// Next *ListNode
_16
// }
_16
func reverse(head *ListNode) *ListNode {
_16
var prev *ListNode
_16
current := head
_16
for current != nil {
_16
next := current.Next
_16
current.Next = prev
_16
prev = current
_16
current = next
_16
}
_16
return prev
_16
}

Merge 2 linked list

  • Recursive approach

_17
func solution(l1 *ListNode, l2 *ListNode) *ListNode {
_17
if l1 == nil {
_17
return l2
_17
}
_17
_17
if l2 == nil {
_17
return l1
_17
}
_17
_17
if l1.Value.(int) <= l2.Value.(int) {
_17
l1.Next = solution(l1.Next, l2)
_17
return l1
_17
} else {
_17
l2.Next = solution(l1, l2.Next)
_17
return l2
_17
}
_17
}

  • Iterative

_35
// Singly-linked lists are already defined with this interface:
_35
// type ListNode struct {
_35
// Value interface{}
_35
// Next *ListNode
_35
// }
_35
//
_35
func solution(l1 *ListNode, l2 *ListNode) *ListNode {
_35
dummy:=&ListNode{}
_35
current := dummy
_35
for {
_35
if (l1 == nil) {
_35
current.Next = l2;
_35
break;
_35
}
_35
if (l2 == nil) {
_35
current.Next = l1;
_35
break;
_35
}
_35
_35
/* Compare the data of the two
_35
lists whichever lists' data is
_35
smaller, append it into tail and
_35
advance the head to the next Node
_35
*/
_35
if (l1.Value.(int) <= l2.Value.(int)) {
_35
current.Next = l1;
_35
l1 = l1.Next;
_35
}else {
_35
current.Next = l2;
_35
l2 = l2.Next;
_35
}
_35
current = current.Next
_35
}
_35
return dummy.Next
_35
}