2016年2月27日 星期六

複習-Linklist 的建制及反轉

#include
#include "stdafx.h"
#include 
#include
#include
#include

using namespace std;
typedef  struct Node
{
 string data;
 struct Node* next;
}LinkList;


LinkList * creatList( string);
LinkList * reverseList(LinkList *);
int main()
{
 string str1;
 LinkList * list = new LinkList;
 cout << "Please input a string:\n";
 cin >> str1;
 list=creatList( str1);
 
 //list = reverseList(list);
 /*for (int i = 0; i < str1.size(); i++)
 {
  cout << str1[i] << endl;
 }*/

 list = reverseList(list);
 cout << endl;
 LinkList * ptr = list;
 while (ptr!=NULL)
 {  
  cout<< ptr->data;
   ptr = ptr->next;
 }
 system("pause");
 return 0;

 //Node* head  =insertNodefromHead(a);
}

LinkList * creatList( string str)
{
 LinkList *head=new LinkList;
 LinkList *ptr = head;

 for (int i = 0; i < str.size(); i++)
 {
  ptr->data = str[i];
  if (i + 1 == str.size())
   ptr->next = NULL;
  else
  {
   ptr->next = new LinkList;
   ptr = ptr->next;
  }
 }
 return head;
}

LinkList * reverseList(LinkList * list)
{
 LinkList *prev=NULL,*curr,*next;
 curr = list; // 放置head為第一個
 while (curr != NULL)
 {
  next = curr->next;
  curr->next = prev;
  prev = curr;
  curr = next;
 }
 return prev;
}

沒有留言:

張貼留言