Skip to content

Instantly share code, notes, and snippets.

@alldroll
Created February 26, 2020 16:52
Show Gist options
  • Select an option

  • Save alldroll/92eb9713e2e694aba3da03c81be5893a to your computer and use it in GitHub Desktop.

Select an option

Save alldroll/92eb9713e2e694aba3da03c81be5893a to your computer and use it in GitHub Desktop.
// https://leetcode.com/problems/reorder-list
/**
* Definition for singly-linked list.
* type ListNode struct {
* Val int
* Next *ListNode
* }
*/
func reorderList(head *ListNode) {
var prev *ListNode
stack := []*ListNode{}
for head != nil {
stack = append(stack, head)
head = head.Next
}
for len(stack) > 0 {
parent := stack[0]
stack = stack[1:]
if prev != nil {
prev.Next = parent
}
if len(stack) > 0 {
child := stack[len(stack) - 1]
stack = stack[:len(stack) - 1]
parent.Next = child
prev = child
prev.Next = nil
} else {
parent.Next = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment