Selaa lähdekoodia

add 'Remove Nth Node From End of List'

tangs 5 vuotta sitten
vanhempi
commit
b1a6827761
1 muutettua tiedostoa jossa 82 lisäystä ja 0 poistoa
  1. 82 0
      tags/linked-list/removeNthNodeFromEndOfList/main.go

+ 82 - 0
tags/linked-list/removeNthNodeFromEndOfList/main.go

@@ -0,0 +1,82 @@
+package main
+
+import "fmt"
+
+func main() {
+	var vals []int
+
+	// empty
+	vals = []int{1}
+	printList(removeNthFromEnd(createList(vals), 1))
+
+	// 1,2,3,4
+	vals = []int{1, 2, 3, 4, 5}
+	printList(removeNthFromEnd(createList(vals), 1))
+
+	// 1,2,3,5
+	vals = []int{1, 2, 3, 4, 5}
+	printList(removeNthFromEnd(createList(vals), 2))
+
+	// 1,2,4,5
+	vals = []int{1, 2, 3, 4, 5}
+	printList(removeNthFromEnd(createList(vals), 3))
+
+	// 1,3,4,5
+	vals = []int{1, 2, 3, 4, 5}
+	printList(removeNthFromEnd(createList(vals), 4))
+
+	// 2,3,4,5
+	vals = []int{1, 2, 3, 4, 5}
+	printList(removeNthFromEnd(createList(vals), 5))
+
+}
+
+func createList(vals []int) *ListNode {
+	var head, list *ListNode
+	for _, v := range vals {
+		if head == nil {
+			list = &ListNode{Val: v, Next: nil}
+			head = list
+			continue
+		}
+		var temp = &ListNode{Val: v, Next: nil}
+		list.Next = temp
+		list = list.Next
+	}
+	return head
+}
+func printList(node *ListNode) {
+	var temp = node
+	for temp != nil {
+		fmt.Printf("%d", temp.Val)
+		if temp.Next != nil {
+			fmt.Printf("%s", "->")
+		}
+		temp = temp.Next
+	}
+	fmt.Println()
+}
+
+// Definition for singly-linked list.
+type ListNode struct {
+	Val  int
+	Next *ListNode
+}
+
+func removeNthFromEnd(head *ListNode, n int) *ListNode {
+	var nth, temp = head, head
+	for i := 0; i < n; i++ {
+		nth = nth.Next
+	}
+	for nth != nil && nth.Next != nil {
+		temp = temp.Next
+		nth = nth.Next
+	}
+	if temp == head && nth == nil {
+		head = head.Next
+		temp = head
+	} else {
+		temp.Next = temp.Next.Next
+	}
+	return head
+}