golang--反转单向链表

1,351 阅读1分钟

type node struct { data int // 数据域 next *node // 指针域 }

type SingleList struct { head *node // 头指针 length int // 单链表长度 }

func TestSingleList(t *testing.T) { s := &SingleList{} s.Insert(2) s.Insert(3) s.Insert(4) s.Reverse() fmt.Println(s.FindAll())

}

func (s *SingleList) Reverse() { if s.IsEmpty() || s.length == 1 { // 为空或者只有一个节点,直接返回 return }

cur := s.head.next // 保存当前节点
var pre *node      // 保存前一个节点
for cur != nil {
	tmp := cur.next // 保存下一个节点
	cur.next = pre  // 调整指针指向
	pre = cur       // 保留pre前进一步,保留前边的节点
	cur = tmp       // curr前进一步,保留当前节点
}
s.head.next = pre
return

}

func (s *SingleList) Insert(data int) { // Insert:向单链表添加某个元素 s.length++ n := &node{ data: data, }

if s.head == nil {	// 表示是空链表
	s.head = &node{}
	s.head.next = n
	return
}

tmp := s.head.next 	// 遍历,然后追加节点
for tmp.next != nil {
	tmp = tmp.next
}
tmp.next = n

}