- Published on
Single linked list trick collection
- Authors
- Name
- Moch Lutfi
- @kaptenupi
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// }_16func 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
_17func 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//_35func 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}