HTMLify

LeetCode - Swapping Nodes in a Linked List - Go
Views: 18 | Author: abh
/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */

func LLLen(head *ListNode) int {
	var len int
	for head != nil {
		head = head.Next
		len++
	}
	return len
}

func swapNodes(head *ListNode, k int) *ListNode {
	var c, l int
	l = LLLen(head)
	h := head
	var fn, ln *ListNode
	for h != nil {
		c++
		if c == k {
			fn = h
		}
		if c == l-k+1 {
			ln = h
		}
		h = h.Next
	}
	fn.Val, ln.Val = ln.Val, fn.Val
	return head
}

Comments