- struct _Node
- {
- int data;
- _Node *next;
- };
- typedef struct _Node Node;
- /*****************************************************
- Test 3: Node *CreateList(Node *head)
- *****************************************************/
- Node *CreateList()
- {
- Node *head = NULL;
- Node *cur = NULL;
- Node *pre = NULL;
- cur=pre=head=(Node*)malloc(sizeof(Node));
- cout<<"Please input the first node:";
- cin>>cur->data;
- cur->next=NULL;/*将新节点的指针置为空*/
- while(cur->data != 0)/*输入节点的数值不等于0*/
- {
- pre->next=cur;/*非空表,接到表尾*/
- pre=cur;
- cur=(Node*)malloc(sizeof(Node));//申请下一个节点
- cout<<"Please input next node(zero to exit):";
- scanf("%d",&cur->data);/*输入节点的值*/
- }
- pre->next = NULL; /*输入cur->data = 0, 抛弃*/
- return head;/*返回链表的头指针*/
- }
- /*****************************************************
- Test 4: void PrintfList(Node *head)
- *****************************************************/
- void PrintList(Node *head)
- {
- Node *cur = head;
- cout<<"List:";
- if(cur == NULL)
- {
- cout<<"NULL"<<endl;
- return;
- }
- while(cur != NULL)
- {
- cout<<"("<<cur->data<<")"<<"->";
- cur = cur->next;
- }
- cout<<endl;
- }
- /*****************************************************
- Test 5: Node * ReverseList(Node *head)
- *****************************************************/
- Node *ReverseList(Node *head)
- {
- if(head == NULL)
- return NULL;
- Node *cur,*pre,*nex = NULL;
- pre = head;
- cur = head->next;
- while(cur != NULL)
- {
- nex = cur->next;
- cur->next = pre;
- pre = cur;
- cur = nex;
- }
- head->next = NULL;
- head = pre;
- return head;
- }
-
- /*****************************************************
- Test 6: Node * ReverseListRecursion(Node *head)
- *****************************************************/
- Node *ReverseListRecursion(Node *head)
{
if(head == NULL || head->next == NULL)
return head; - Node *newHead = ReverseListRecursion(head->next);
head->next->next = head;
head->next = NULL; - return newHead;
}
调用
- /*****************************************************
- Test : Node *CreateList(Node *head)
- *****************************************************/
- Node *list = CreateList();
- /*****************************************************
- Test : void PrintfList(Node *head)
- *****************************************************/
- cout<<"The List looks like this:"<<endl;
- PrintList(list);
- /*****************************************************
- Test : Node * ReverseList(Node *head)
- *****************************************************/
- //Node *reverselist = ReverseList(list);
- //PrintList(reverselist);
- Node *reverselistRecursion = ReverseListRecursion(reverselist);
- PrintList(reverselistRecursion);
- System("pause");
截屏