reverse a linked list

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;

}

你可能感兴趣的:(reverse a linked list)