찾다
백엔드 개발Golanggolang은 이중 연결 목록을 구현합니다.

이중 연결 목록은 O(1) 시간 복잡도 내에서 연결 목록의 어느 위치에서나 삽입, 삭제 또는 쿼리 작업을 수행할 수 있도록 일반적으로 사용되는 데이터 구조입니다.

Golang에서 이중 연결 목록을 구현하려면 포인터를 사용해야 합니다. Golang의 모든 유형은 값 유형이고 원본 데이터를 직접 수정할 수 없기 때문입니다. 포인터를 통해 값을 쉽게 수정하고 전달할 수 있으므로 이중 연결 목록의 작동을 실현할 수 있습니다.

다음은 이중 연결 목록의 간단한 Golang 구현입니다.

package main

import "fmt"

type Node struct {
    data     int
    previous *Node
    next     *Node
}

type LinkedList struct {
    head *Node
    tail *Node
}

func (list *LinkedList) insertAtBeginning(data int) {
    newNode := &Node{
        data:     data,
        previous: nil,
        next:     nil,
    }

    if list.head == nil {
        list.head = newNode
        list.tail = newNode
        return
    }

    newNode.next = list.head
    list.head.previous = newNode
    list.head = newNode
}

func (list *LinkedList) insertAtEnd(data int) {
    newNode := &Node{
        data:     data,
        previous: nil,
        next:     nil,
    }

    if list.tail == nil {
        list.head = newNode
        list.tail = newNode
        return
    }

    newNode.previous = list.tail
    list.tail.next = newNode
    list.tail = newNode
}

func (list *LinkedList) delete(data int) bool {
    currentNode := list.head

    for currentNode != nil {
        if currentNode.data == data {
            if currentNode == list.head {
                list.head = currentNode.next
                list.head.previous = nil
            } else if currentNode == list.tail {
                list.tail = currentNode.previous
                list.tail.next = nil
            } else {
                currentNode.previous.next = currentNode.next
                currentNode.next.previous = currentNode.previous
            }

            return true
        }

        currentNode = currentNode.next
    }

    return false
}

func (list *LinkedList) display() {
    currentNode := list.head

    for currentNode != nil {
        fmt.Printf("%d ", currentNode.data)
        currentNode = currentNode.next
    }

    fmt.Println()
}

func main() {
    list := LinkedList{}

    list.insertAtEnd(1)
    list.insertAtEnd(2)
    list.insertAtEnd(3)
    list.insertAtBeginning(4)

    list.display()

    list.delete(3)

    list.display()
}

위 코드에서는 먼저 연결 목록의 각 노드에 필요한 정보가 포함된 Node 구조를 정의합니다. 데이터: 데이터, 이전다음. 그 중 data는 노드의 값을 저장하고, previous는 이전 노드의 주소를 저장하고, next는 다음 노드의 주소를 저장합니다. . Node 结构体,该结构体包含链表中的每个节点所需的三个数据:datapreviousnext。其中,data 存储节点的值,previous 存储上一个节点的地址,next 存储下一个节点的地址。

然后,我们定义了一个 LinkedList 结构体来表示整个链表。该结构体包含链表的头指针 head 和尾指针 tail

下面是实现双向链表所需的几个方法:

// 在链表头部插入一个元素
func (list *LinkedList) insertAtBeginning(data int) {
    newNode := &Node{
        data:     data,
        previous: nil,
        next:     nil,
    }

    if list.head == nil {
        list.head = newNode
        list.tail = newNode
        return
    }

    newNode.next = list.head
    list.head.previous = newNode
    list.head = newNode
}

// 在链表尾部插入一个元素
func (list *LinkedList) insertAtEnd(data int) {
    newNode := &Node{
        data:     data,
        previous: nil,
        next:     nil,
    }

    if list.tail == nil {
        list.head = newNode
        list.tail = newNode
        return
    }

    newNode.previous = list.tail
    list.tail.next = newNode
    list.tail = newNode
}

// 删除链表中指定的元素
func (list *LinkedList) delete(data int) bool {
    currentNode := list.head

    for currentNode != nil {
        if currentNode.data == data {
            if currentNode == list.head {
                list.head = currentNode.next
                list.head.previous = nil
            } else if currentNode == list.tail {
                list.tail = currentNode.previous
                list.tail.next = nil
            } else {
                currentNode.previous.next = currentNode.next
                currentNode.next.previous = currentNode.previous
            }

            return true
        }

        currentNode = currentNode.next
    }

    return false
}

// 打印链表的所有元素
func (list *LinkedList) display() {
    currentNode := list.head

    for currentNode != nil {
        fmt.Printf("%d ", currentNode.data)
        currentNode = currentNode.next
    }

    fmt.Println()
}

在定义了这几个方法后,我们可以在 main 函数中实例化一个链表对象并进行操作:

func main() {
    list := LinkedList{}

    list.insertAtEnd(1)
    list.insertAtEnd(2)
    list.insertAtEnd(3)
    list.insertAtBeginning(4)

    list.display()

    list.delete(3)

    list.display()
}

在上面的代码中,我们首先实例化了一个 LinkedList 对象 list,然后我们按顺序插入了四个元素:1、2、3 和 4。我们在第一次调用 display 方法时,将输出链表的内容:

4 1 2 3

接着,我们删除了元素 3,并再次调用 display

그런 다음 전체 연결 목록을 나타내기 위해 LinkedList 구조를 정의합니다. 이 구조에는 연결된 목록의 헤드 포인터 head와 꼬리 포인터 tail가 포함되어 있습니다.

다음은 이중 연결 목록을 구현하는 데 필요한 몇 가지 메서드입니다. 🎜
4 1 2
🎜이러한 메서드를 정의한 후 main 함수에서 연결 목록 개체를 인스턴스화하고 작업을 수행할 수 있습니다. 🎜rrreee 🎜In the 위 코드에서는 먼저 LinkedList 개체 list를 인스턴스화한 다음 4개 요소(1, 2, 3, 4)를 순서대로 삽입합니다. display 메서드를 처음 호출하면 연결 목록의 내용이 출력됩니다. 🎜rrreee🎜그런 다음 요소 3을 삭제하고 display 메서드를 다시 호출합니다. 연결 목록의 내용을 출력하려면 최신 콘텐츠: 🎜rrreee🎜이중 연결 목록의 간단한 Golang 구현은 포인터를 사용하여 연결 목록을 만들고 수정하는 방법과 연결 목록의 삽입, 삭제 및 쿼리와 같은 작업을 구현하는 방법을 보여줍니다. . 효율적인 데이터 구조를 만들기 위해 이중 연결 목록을 사용해야 하는 경우 위의 코드를 참조하여 Golang에서 이중 연결 목록을 구현하는 방법을 알아보세요. 🎜

위 내용은 golang은 이중 연결 목록을 구현합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Golang과 Python : 차이점을 이해합니다Golang과 Python : 차이점을 이해합니다Apr 18, 2025 am 12:21 AM

Golang과 Python의 주요 차이점은 동시성 모델, 유형 시스템, 성능 및 실행 속도입니다. 1. Golang은 동시 작업에 적합한 CSP 모델을 사용합니다. Python은 I/O 집약적 인 작업에 적합한 멀티 스레딩 및 Gil에 의존합니다. 2. Golang은 정적 유형이며 Python은 동적 유형입니다. 3. Golang 컴파일 된 언어 실행 속도는 빠르며 파이썬 해석 언어 개발은 ​​빠릅니다.

Golang vs. C : 속도 차이 평가Golang vs. C : 속도 차이 평가Apr 18, 2025 am 12:20 AM

Golang은 일반적으로 C보다 느리지 만 Golang은 동시 프로그래밍 및 개발 효율에 더 많은 장점이 있습니다. 1) Golang의 쓰레기 수집 및 동시성 모델은 높은 동시 시나리오에서 잘 수행합니다. 2) C는 수동 메모리 관리 및 하드웨어 최적화를 통해 더 높은 성능을 얻지 만 개발 복잡성이 높습니다.

Golang : 클라우드 컴퓨팅 및 DevOps의 핵심 언어Golang : 클라우드 컴퓨팅 및 DevOps의 핵심 언어Apr 18, 2025 am 12:18 AM

Golang은 클라우드 컴퓨팅 및 DevOps에서 널리 사용되며 장점은 단순성, 효율성 및 동시 프로그래밍 기능에 있습니다. 1) 클라우드 컴퓨팅에서 Golang은 Goroutine 및 채널 메커니즘을 통해 동시 요청을 효율적으로 처리합니다. 2) DevOps에서 Golang의 빠른 편집 및 크로스 플랫폼 기능이 자동화 도구의 첫 번째 선택입니다.

Golang 및 C : 실행 효율성 이해Golang 및 C : 실행 효율성 이해Apr 18, 2025 am 12:16 AM

Golang과 C는 각각 성능 효율성에서 고유 한 장점을 가지고 있습니다. 1) Golang은 Goroutine 및 Garbage Collection을 통해 효율성을 향상 시키지만 일시 중지 시간을 도입 할 수 있습니다. 2) C는 수동 메모리 관리 및 최적화를 통해 고성능을 인식하지만 개발자는 메모리 누출 및 기타 문제를 처리해야합니다. 선택할 때는 프로젝트 요구 사항 및 팀 기술 스택을 고려해야합니다.

Golang vs. Python : 동시성 및 멀티 스레딩Golang vs. Python : 동시성 및 멀티 스레딩Apr 17, 2025 am 12:20 AM

Golang은 높은 동시성 작업에 더 적합하지만 Python은 유연성에 더 많은 장점이 있습니다. 1. Golang은 Goroutine 및 채널을 통해 동시성을 효율적으로 처리합니다. 2. Python은 GIL의 영향을받는 스레딩 및 Asyncio에 의존하지만 여러 동시성 방법을 제공합니다. 선택은 특정 요구 사항을 기반으로해야합니다.

Golang 및 C : 성능 상충Golang 및 C : 성능 상충Apr 17, 2025 am 12:18 AM

Golang과 C의 성능 차이는 주로 메모리 관리, 컴파일 최적화 및 런타임 효율에 반영됩니다. 1) Golang의 쓰레기 수집 메커니즘은 편리하지만 성능에 영향을 줄 수 있습니다. 2) C의 수동 메모리 관리 및 컴파일러 최적화는 재귀 컴퓨팅에서 더 효율적입니다.

Golang vs. Python : 응용 프로그램 및 사용 사례Golang vs. Python : 응용 프로그램 및 사용 사례Apr 17, 2025 am 12:17 AM

선택 GOLANGFORHIGHERFERFERFORMANDCONDCURRENCY, TILDFORBECTERVICES 및 NNETWORKPRAMPHING; SELECTPYTHONFORRAPIDDEVENTURMENT, DATASCIENCE 및 MACHINEARNINGDUETOITSTINTIVENDEXTENDIVERIRIES.

Golang vs. Python : 주요 차이점과 유사성Golang vs. Python : 주요 차이점과 유사성Apr 17, 2025 am 12:15 AM

Golang과 Python은 각각 고유 한 장점이 있습니다. Golang은 고성능 및 동시 프로그래밍에 적합하지만 Python은 데이터 과학 및 웹 개발에 적합합니다. Golang은 동시성 모델과 효율적인 성능으로 유명하며 Python은 간결한 구문 및 풍부한 라이브러리 생태계로 유명합니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

PhpStorm 맥 버전

PhpStorm 맥 버전

최신(2018.2.1) 전문 PHP 통합 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

Atom Editor Mac 버전 다운로드

Atom Editor Mac 버전 다운로드

가장 인기 있는 오픈 소스 편집기

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구