Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【算法系列 - 剑指Offer】从尾到头打印链表 #15

Open
AwesomeDevin opened this issue Jun 12, 2019 · 0 comments
Open

【算法系列 - 剑指Offer】从尾到头打印链表 #15

AwesomeDevin opened this issue Jun 12, 2019 · 0 comments

Comments

@AwesomeDevin
Copy link
Owner

AwesomeDevin commented Jun 12, 2019

题目

输入一个链表,返回一个反序的链表。

思路

使用generateLinkList生成链表linklist,对链表linklist进行reverse

JS实现

class ListNode{
	constructor(nextIndex,val){
		this.nextIndex = nextIndex
		this.val = val
	}
}


function generateLinkList(length){    //generate linklist
	var list = []
	for(var i=0;i<length;i++)
	{
		// console.log(i)
		var listnode = new ListNode(i+1,i)
		list.push(listnode)
		// console.log(listnode)
	}
	return list
}


const linklist = generateLinkList(10)


function main(linkList){    //reverse linklist
	const result = []
	for(var index=0;index<linkList.length;index++)
	{
		// linkList[index].val 
		var listnode = new ListNode(linkList[index].nextIndex,linkList[linkList.length-index-1].val)
		result.push(listnode)
	}
	return result
}


console.log(main(linklist))
/*function ListNode(x){
    this.val = x;
    this.next = null;
}*/
function printListFromTailToHead(head)
{
    if(!head)
    {
        return 0
    }
    var res = []
    while(head)
    {
        res.push(head.val)
        head = head.next
    }
    return res.reverse()
}
@AwesomeDevin AwesomeDevin changed the title 【算法系列】从尾到头打印链表 【算法系列 - 剑指offer】从尾到头打印链表 Jun 12, 2019
@AwesomeDevin AwesomeDevin changed the title 【算法系列 - 剑指offer】从尾到头打印链表 【算法系列 - 剑指Offer】从尾到头打印链表 Jun 12, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant