链表 -- 反转 (递归 + 非递归)

#include<iostream>
#include<stdio.h>
using namespace std;

typedef struct lnode{
    int data;
    struct lnode * next;
}node;
void createLink(node *&head)
{
    int x;
    node * p = head;
    while (scanf("%d", &x) != EOF)
    {
        node * q = new node;
        q->data = x;
        if (head == NULL)
        {
           head = q;
           head->next = NULL;
           p = head;
        }
        else
        {
           q->next = p->next;
           p->next = q;
           p = q;
        }
    }
}

void output(node * head)
{
   node * p = head;
   while(p != NULL)
   {
       cout<<p->data<<" ";
       p = p->next;
   }
   cout<<endl;
}

 
 
void reverseoutput(node * head)
{
  if (head != NULL)
  {
      reverseoutput(head->next); 
      printf("%d ", head->data);
  }
}
node * reverseLink2(node * head, node *& newhead)
{
   if (head->next == NULL ||  head == NULL)
   {
       newhead = head;
       return head;
   }
   else
   {
       node * p = reverseLink2(head->next, newhead);
       p->next = head;
       head->next = NULL;
       return head;
   }
}

node * reverseLink(node *& oldhead)
{
   node * p, * newhead;

   newhead = NULL;
   p = newhead;
   while (oldhead!= NULL)
   {
       newhead = oldhead;
       oldhead = oldhead->next;
       newhead->next = p;
       p = newhead;
   }
   return newhead;
}

int main(void)
{
   node * head = NULL;
   node * newhead = NULL;
   node * newhead2 = NULL;
   createLink(head);
   output(head);
   newhead = reverseLink(head);
   output(newhead);
   reverseLink2(newhead, newhead2);
   output(newhead2);
}


 

你可能感兴趣的:(链表 -- 反转 (递归 + 非递归))