zoukankan      html  css  js  c++  java
  • Go语言(Golang)双链表

    package main
    
    import (
    	"fmt"
    )
    
    //双链表结构
    type TwoLinkTable struct {
    	no int 
    	name string
    	pre *TwoLinkTable
    	next *TwoLinkTable
    }
    
    //直接在队尾插入
    func InsertNode(head *TwoLinkTable, newNode *TwoLinkTable) {
    	temp := head
    	
    	for {
    		if temp.next == nil {
    			break
    		}
    		temp = temp.next
    	}
    	temp.next = newNode
    	newNode.pre = temp
    }
    
    //按编号no从小到大顺序插入
    func InsertNode2(head *TwoLinkTable, newNode *TwoLinkTable) {
    	temp := head
    	
    	for {
    		if temp.next == nil {
    			break
    		}else if temp.next.no >= newNode.no {
    			break
    		}
    		temp = temp.next
    	}
    
    	newNode.next = temp.next
    	newNode.pre = temp
    	if temp.next != nil {
    		temp.next.pre = newNode
    	}
    	temp.next = newNode
    	
    }
    
    //按no编号删除
    func DelNode(head *TwoLinkTable, id int) {
    	temp := head
    	if temp.next == nil {
    		fmt.Println("该队列为空!")
    		return
    	}
    
    	for {
    		if temp.next == nil {
    			break
    		} else if temp.next.no == id {
    			if temp.next.next != nil {
    				temp.next.next.pre = temp
    			}
    			temp.next = temp.next.next
    			return
    		}
    		temp = temp.next
    	}
    	fmt.Println("未找到该编号的对象")
    }
    
    //正序显示
    func ListNodeASC(head *TwoLinkTable) {
    	temp := head
    	if temp.next == nil {
    		fmt.Println("该队列为空!")
    		return
    	}
    	for {
    		if temp.next == nil {
    			break
    		}
    		fmt.Printf("%d:%s\t",temp.next.no,temp.next.name)
    		temp = temp.next
    	}
    }
    
    
    //倒序显示
    func ListNodeDESC(head *TwoLinkTable) {
    	temp := head
    	if temp.next == nil {
    		fmt.Println("该队列为空!")
    		return
    	}
    	for {
    		if temp.next == nil {
    			break
    		}
    		temp = temp.next
    	}
    	for {
    		fmt.Printf("%d:%s\t",temp.no,temp.name)
    		temp = temp.pre
    		if temp.pre == nil {
    			break
    		}
    	}
    }
    
    func main() {
    	head := &TwoLinkTable{}
    
    	newNode1 := &TwoLinkTable {
    		no : 1,
    		name : "a",
    	}
    	newNode2 := &TwoLinkTable {
    		no : 2,
    		name : "b",
    	}
    	newNode3 := &TwoLinkTable {
    		no : 3,
    		name : "c",
    	}
    	InsertNode2(head, newNode2)
    	InsertNode2(head, newNode1)
    	InsertNode2(head, newNode3)
    	DelNode(head,3)
    	fmt.Println("正序:")
    	ListNodeASC(head)
    	fmt.Println("\n逆序:")
    	ListNodeDESC(head)
    }
    

      

  • 相关阅读:
    RSA
    antd 规则检查
    antd 使用总结问题
    react context prop-types
    【CSS/JS】如何实现单行/多行文本溢出的省略(...)
    react prop-types
    js 监听URL的hash变化
    Spark 读取Hadoop集群文件
    HIVE 常见函数
    Linux ANSI转 UTF8
  • 原文地址:https://www.cnblogs.com/HouZhenglan/p/10077400.html
Copyright © 2011-2022 走看看