Skip to content

Commit c445932

Browse files
committed
added circular-linked-list
1 parent 7da54c3 commit c445932

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// ====================================================
2+
// Data-Structures-with-Go Copyright(C) 2017 Furkan Türkal
3+
// This program comes with ABSOLUTELY NO WARRANTY; This is free software,
4+
// and you are welcome to redistribute it under certain conditions; See
5+
// file LICENSE, which is part of this source code package, for details.
6+
// ====================================================
7+
8+
package main
9+
10+
import "fmt"
11+
12+
type Node struct {
13+
data int
14+
next *Node
15+
}
16+
17+
//Returns an initialized list
18+
func (n *Node) Init() *Node {
19+
n.data = -1
20+
return n
21+
}
22+
23+
//Returns an new list
24+
func New() *Node {
25+
return new(Node).Init()
26+
}
27+
28+
//Returns the first node in list
29+
func (n *Node) Next() *Node {
30+
return n.next
31+
}
32+
33+
//Returns the last node in list if exist, otherwise returns current
34+
func (n *Node) Back() *Node {
35+
current := n.next
36+
for current != nil && current.next != nil {
37+
current = current.next
38+
}
39+
return current
40+
}
41+
42+
//This function prints contents of linked list starting from the given node
43+
func printList(n *Node) {
44+
for n != nil {
45+
fmt.Println(n.data)
46+
n = n.next
47+
}
48+
}
49+
50+
func Push(head_ref **Node, new_data int) {
51+
//1. Allocate new node
52+
new_node := New()
53+
temp := *head_ref
54+
55+
new_node.data = new_data
56+
new_node.next = *head_ref
57+
58+
//2. If linked list is not NULL then set the next of last node
59+
if *head_ref != nil {
60+
for temp.next != *head_ref {
61+
temp = temp.next
62+
}
63+
temp.next = new_node
64+
} else {
65+
//For the fist node
66+
new_node.next = new_node
67+
}
68+
//4. Move the head to point to new_node
69+
*head_ref = new_node
70+
}
71+
72+
func main() {
73+
//Start with the empty list
74+
head := New()
75+
76+
Push(&head, 12)
77+
Push(&head, 56)
78+
Push(&head, 2)
79+
Push(&head, 11)
80+
81+
fmt.Println("Created Circular LinkedList is: ")
82+
83+
printList(head)
84+
}

0 commit comments

Comments
 (0)