Introduction to Algorithms exercise: 10.2-7 in Go language

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

10.2-7: A non-recursive process with a time complexity of O (n) is given to reverse the single-linked list with n elements.

The main idea of the program is that the direction of the transformation indicators, such as the original 1->2->3->4, now become 1<-2<-3<-4, has been reversed


Package Mainimport ("FMT") type Node struct {Next *node data int}type List struct {first *node}func (l *list) I  Nsert (d int) {node: = &node{nil, d} node.next = L.first l.first = node}func revise (L *list) {if L.first = = Nil {return} Curr: = L.first Next: = Curr.next Curr.next = nil for {L AST: = Curr Curr = Next Next = Curr.next Curr.next = Last if NE XT = = Nil {L.first = Curr Break}}}func Printlist (l *list) {if L.first = = Nil {fmt. Println ("The list is empty") return} FMT. Print ("list:") for node: = L.first; Node! = Nil; {FMT. Printf ("[%d]", node.data) node = node.next} fmt. Print ("\ n")}func main () {list: = &list{nil} for I: = 0; i <; i++ {list. Insert (i)} printlist (list) revise (list) PrintliSt (list)} 


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.