编程练习- 链表题目-反序,合并
Code Snippet
- #include <iostream>
- #include<fstream>
- using namespace std;
- struct Node
- {
- int data ;
- Node *next ;
- };
- typedef struct Node Node ;
- void ReverseList(Node*& head)
- {
- if(head == NULL || head->next == NULL)
- return;
- Node* currentNode = head;
- Node* previousNode = NULL;
- while(currentNode != NULL)
- ...{
- Node* temp = currentNode->next;
- currentNode->next = previousNode;
- previousNode = currentNode;
- currentNode = temp;
- }
- head = previousNode;
- }
- // My answer.
- Node* MergeLinkList(Node* listA, Node* listB)
- {
- if(listA == NULL)
- return listB;
- if(listB == NULL)
- return listA;
- Node* pHeadSmall = listA -> data < listB -> data ? listA : listB;
- Node* pHeadBig = pHeadSmall == listA ? listB : listA;
- Node* p = pHeadSmall;
- Node* q = pHeadSmall->next;
- Node* r = pHeadBig;
- while(q != NULL && r != NULL)
- ...{
- if(q->data <= r->data)
- ...{
- p->next = q;
- p = p->next;
- q = q->next;
- }
- else
- ...{
- p->next = r;
- p = p->next;
- r = r->next;
- }
- }
- if(q == NULL)
- {
- p->next = r;
- }
- else
- {
- p->next = q;
- }
- return pHeadSmall;
- }
- // Standard answer
- Node * Merge(Node *head1 , Node *head2)
- {
- if ( head1 == NULL)
- return head2 ;
- if ( head2 == NULL)
- return head1 ;
- Node *head = NULL ;
- Node *p1 = NULL;
- Node *p2 = NULL;
- if ( head1->data < head2->data )
- {
- head = head1 ;
- p1 = head1->next;
- p2 = head2 ;
- }
- else
- {
- head = head2 ;
- p2 = head2->next ;
- p1 = head1 ;
- }
- Node *pcurrent = head ;
- while ( p1 != NULL && p2 != NULL)
- {
- if ( p1->data <= p2->data )
- {
- pcurrent->next = p1 ;
- pcurrent = p1 ;
- p1 = p1->next ;
- }
- else
- {
- pcurrent->next = p2 ;
- pcurrent = p2 ;
- p2 = p2->next ;
- }
- }
- if ( p1 != NULL )
- pcurrent->next = p1 ;
- if ( p2 != NULL )
- pcurrent->next = p2 ;
- return head ;
- }
- // Utillity function.
- void TestList(Node* head)
- {
- Node* p = head;
- while(p != NULL)
- {
- cout << p->data << endl;;
- p= p->next;
- }
- }
- // Utillity function.
- Node* InputList(ifstream& inFile)
- {
- int len;
- inFile >> len;
- Node* head = new Node[len];
- Node* p = head;
- for(int i = 0; i < len - 1; i++)...{
- inFile >> p->data;
- p->next = p + 1;
- p = p->next;
- }
- inFile >> p->data;
- p->next = NULL;
- return head;
- }
- int main()
- {
- ifstream inFile("d:\data.txt");
- if(!inFile)
- return -1;
- Node* headA = InputList(inFile);
- Node* headB = InputList(inFile);
- TestList(headA);
- TestList(headB);
- ReverseList(headA);
- cout<< "Testing Reverse A" << endl;
- TestList(headA);
- ReverseList(headA);
- cout<< "Testing Reverse A back." << endl;
- TestList(headA);
- Node* newHead = Merge(headA, headB);
- cout<< "Testing Merged List." << endl;
- TestList(newHead);
- while(newHead != NULL)
- {
- Node* ptr = newHead;
- newHead = newHead->next;
- delete ptr;
- }
- }