【数据结构】链表的基本学习 实现

package test;

import (
	"testing"
	"fmt"
)

type InteegetCell struct{
	Value int
	Next *InteegetCell
}

// 初始化链表(建立一个头指针)
func initCell() *InteegetCell{
	return new(InteegetCell)
}

// 头插法追加元素
func AddAtBeginning(top *InteegetCell, value int){
	newCell := &InteegetCell{value,top.Next}
	top.Next = newCell
}

// 尾插法的实现
func AddAtTali(top *InteegetCell, value int){
	for top.Next != nil {
		top = top.Next
	}
	newCell := &InteegetCell{value,nil}
	top.Next = newCell
}

// 变历链表
func Interte(top *InteegetCell){
	var result []int
	for top != nil {
		value := top.Value
		result = append(result, value)
		top = top.Next
	}	
	fmt.Println(result)	
	
}



func Test(t *testing.T){
	top := initCell()

	// fmt.Println("-----测试头插法-----")
	// for i:=1; i<4; i++ {
	// 	AddAtBeginning(top,i)
	// }
	// // 遍历链表
	// Interte(top)

	fmt.Println("-----测试尾插法-----")
	AddAtTali(top,1)
	AddAtTali(top,2)
	AddAtTali(top,3)
	Interte(top)

	

}



package com.ndz.garbage;

public class ListNode {

    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }

    // 尾插法
    public static void addAtTali(ListNode top, int value) {
        while (top.next != null) {
            top = top.next;
        }
        ListNode newNode = new ListNode(value);
        top.next = newNode;
    }

   public static void visit(ListNode node){
        while (node.next != null) {
            node = node.next;
            System.out.print(node.val+" ");
        }
        System.out.println();

    }

    public static void main(String[] args) {
        ListNode head = new ListNode(0);

        for (int i = 1; i < 6; i++) {
            addAtTali(head, i);
        }

        visit(head);

    }
}


“年轻时,我没受过多少系统教育,但什么书都读。读得最多的是诗,包括烂诗,我坚信烂诗早晚会让我邂逅好诗。” by. 马尔克斯
原文地址:https://www.cnblogs.com/jzsg/p/10963916.html