单链表制定区域倒序时间复杂度O(n)

有序链表
0,1,2,3,4,5,6
倒序制定区域
例如recover(0,1)
特别注意在0 开始的时候 和大于结束节点的时候

package main

import (
	"fmt"
)

type Nextn interface {
	NextNode() *Node
}

type Node struct {
	Data string
	Next *Node
}

type List struct {
	HeadNode *Node
	Len      int
}

func newList() *List {
	list := &List{HeadNode: nil}
	return list
}

func (l *List) Lenght() int {
	return l.Len
}

func (l *List) insert(data string) {
	node := Node{Data: data, Next: nil}
	node.Next = l.HeadNode
	l.HeadNode = &node
	l.Len = l.Len + 1
}

func (l *List) IsEmpty() bool {
	if l.HeadNode == nil {
		return true
	}
	return false
}

func (n *Node) NextNode() (*Node, bool) {
	if n.Next == nil {
		return nil, false
	}
	return n.Next, true
}

func (l *List) GetHeadNode() (*Node, bool) {
	if l.HeadNode == nil {
		return nil, false
	}
	return l.HeadNode, true
}

func (l *List) NextNode() (*Node, bool) {
	if l.HeadNode == nil {
		return nil, false
	}
	return l.HeadNode, true
}

func (l *List) recover(i, j int) {
	if l.IsEmpty() {
		panic("list is empty")
	}
	if i >= j {
		return
	}
	if i < 0 {
		i = 0
	}
	index := 0
	headNode, _ := l.GetHeadNode()
	var curNode *Node
	var StartttNode *Node
	var StarttNode *Node
	if l.Lenght() <= j {
		j = l.Lenght()
	}
	curNode = headNode
	for {
		if index == j {
			fmt.Println("end-index", index)
			break
		}
		if index == i-1 {
			StartttNode = curNode
		}
		if index == i {
			StarttNode = curNode
		}
		nextNode, ok := curNode.NextNode()
		if index >= i && ok {
			curNode.Next = nextNode.Next
			nextNode.Next = StarttNode
			StarttNode = nextNode
			if i == 0 {
				l.HeadNode = nextNode
			} else {
				StartttNode.Next = nextNode
			}
			curNode = curNode
		}
		if index < i {
			curNode = nextNode
		}
		index = index + 1
	}
}

func swap(start, end int, S []string) {
	S[start], S[end] = S[end], S[start]
}

func permutation(S []string, start, end int) {
	if start == end-1 {
		fmt.Println(S)
	} else {
		for i := start; i < end; i++ {
			swap(start, i, S)            // 交换
			permutation(S, start+1, end) //子集合
			swap(i, start, S)            //回朔
		}
	}
}

func main() {
	// permutation([]string{"1", "2", "3"}, 0, 3)
	list := newList()
	list.insert("6")
	list.insert("5")
	list.insert("4")
	list.insert("3")
	list.insert("2")
	list.insert("1")
	list.insert("0")
	list.recover(0, 8)
	node, ok := list.NextNode()
	index := 0
	if ok {
		for {
			if index > list.Len {
				return
			}
			fmt.Println(node.Data)
			node, _ = node.NextNode()
			if node == nil {
				return
			}
			index = index + 1
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值