mirror of https://github.com/01-edu/public.git
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
87 lines
1.4 KiB
87 lines
1.4 KiB
5 years ago
|
## listforeach
|
||
6 years ago
|
|
||
6 years ago
|
### Instructions
|
||
6 years ago
|
|
||
5 years ago
|
Write a function `ListForEach` that applies a function given as argument to the data within each node of the list `l`.
|
||
6 years ago
|
|
||
5 years ago
|
- The function given as argument must have a pointer as argument: `l *List`
|
||
5 years ago
|
|
||
5 years ago
|
- Copy the functions `Add2_node` and `Subtract3_node` in the same file as the function `ListForEach` is defined.
|
||
6 years ago
|
|
||
6 years ago
|
### Expected function and structure
|
||
6 years ago
|
|
||
|
```go
|
||
5 years ago
|
type NodeL struct {
|
||
|
Data interface{}
|
||
|
Next *NodeL
|
||
|
}
|
||
|
|
||
|
type List struct {
|
||
|
Head *NodeL
|
||
|
Tail *NodeL
|
||
6 years ago
|
}
|
||
|
|
||
5 years ago
|
func ListForEach(l *List, f func(*NodeL)) {
|
||
6 years ago
|
}
|
||
|
|
||
5 years ago
|
func Add2_node(node *NodeL) {
|
||
|
switch node.Data.(type) {
|
||
|
case int:
|
||
|
node.Data = node.Data.(int) + 2
|
||
|
case string:
|
||
|
node.Data = node.Data.(string) + "2"
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func Subtract3_node(node *NodeL) {
|
||
|
switch node.Data.(type) {
|
||
|
case int:
|
||
|
node.Data = node.Data.(int) - 3
|
||
|
case string:
|
||
|
node.Data = node.Data.(string) + "-3"
|
||
|
}
|
||
6 years ago
|
}
|
||
|
```
|
||
|
|
||
6 years ago
|
### Usage
|
||
6 years ago
|
|
||
5 years ago
|
Here is a possible program to test your function :
|
||
6 years ago
|
|
||
|
```go
|
||
|
package main
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
piscine ".."
|
||
|
)
|
||
|
|
||
|
func main() {
|
||
5 years ago
|
link := &piscine.List{}
|
||
6 years ago
|
|
||
5 years ago
|
piscine.ListPushBack(link, "1")
|
||
|
piscine.ListPushBack(link, "2")
|
||
|
piscine.ListPushBack(link, "3")
|
||
|
piscine.ListPushBack(link, "5")
|
||
6 years ago
|
|
||
5 years ago
|
piscine.ListForEach(link, piscine.Add2_node)
|
||
6 years ago
|
|
||
5 years ago
|
it := link.Head
|
||
|
for it != nil {
|
||
|
fmt.Println(it.Data)
|
||
|
it = it.Next
|
||
6 years ago
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
And its output :
|
||
|
|
||
|
```console
|
||
5 years ago
|
student@ubuntu:~/[[ROOT]]/test$ go build
|
||
|
student@ubuntu:~/[[ROOT]]/test$ ./test
|
||
5 years ago
|
12
|
||
|
22
|
||
|
32
|
||
|
52
|
||
5 years ago
|
student@ubuntu:~/[[ROOT]]/test$
|
||
6 years ago
|
```
|