Marshal top-level nils correctly.

Merge rogpeppe's branch '001-allow-nil-marshal'.
diff --git a/decode.go b/decode.go
index deba771..a098626 100644
--- a/decode.go
+++ b/decode.go
@@ -544,7 +544,7 @@
 		d.unmarshal(n, out)
 	case sequenceNode:
 		// Step backwards as earlier nodes take precedence.
-		for i := len(n.children)-1; i >= 0; i-- {
+		for i := len(n.children) - 1; i >= 0; i-- {
 			ni := n.children[i]
 			if ni.kind == aliasNode {
 				an, ok := d.doc.anchors[ni.value]
diff --git a/encode.go b/encode.go
index 4a57ee3..0b9048d 100644
--- a/encode.go
+++ b/encode.go
@@ -57,6 +57,10 @@
 }
 
 func (e *encoder) marshal(tag string, in reflect.Value) {
+	if !in.IsValid() {
+		e.nilv()
+		return
+	}
 	var value interface{}
 	if getter, ok := in.Interface().(Getter); ok {
 		tag, value = getter.GetYAML()
diff --git a/encode_test.go b/encode_test.go
index 9f745c9..c9febc2 100644
--- a/encode_test.go
+++ b/encode_test.go
@@ -2,12 +2,13 @@
 
 import (
 	"fmt"
-	. "gopkg.in/check.v1"
-	"gopkg.in/yaml.v1"
 	"math"
 	"strconv"
 	"strings"
 	"time"
+
+	. "gopkg.in/check.v1"
+	"gopkg.in/yaml.v1"
 )
 
 var marshalIntTest = 123
@@ -17,6 +18,9 @@
 	data  string
 }{
 	{
+		nil,
+		"null\n",
+	}, {
 		&struct{}{},
 		"{}\n",
 	}, {