现在的位置: 首页 > 综合 > 正文

reverse a linked list

2013年05月30日 ⁄ 综合 ⁄ 共 1154字 ⁄ 字号 评论关闭

Question: Write a function (in C# or C++)to reverse a linked list.

           Given a data structure:

       C++:

                       class Node

                       {

                       public:

                                   int data;

                                   Node* next;

                       };

       C#:

              classNode

              {

                     publicint data;

                     publicNode next;

              };

           Implement the function:

       InC++:

              Node*Reverse (Node* head)

              {

                     …

              }

       InC#:

                       Node Reverse (Node head)

                       {

                                   …

                       }

           It takes in the head of the linked list and is supposed to reverse the linkedlist and returns the new head.

//=====================================================

Node*reverse(Node *head){

        Node *tmp = head;

 

        Node *prev = 0;

        Node *tmpNext = tmp->next;

        while(tmp != 0){

                tmp->next = prev;

                if(tmpNext == 0) break;

                prev = tmp;

                tmp = tmpNext;

                tmpNext = tmp->next;

        }

 

        head = tmp;

        return head;

}

抱歉!评论已关闭.