130.一个链表的结点结构
struct Node
{
int data ;
Node *next ;
};
typedef struct Node Node ;
已知链表的头结点head,写一个函数把这个链表逆序 ( Intel)
struct Node
{
int data ;
Node *next ;
};
typedef struct Node Node ;
已知链表的头结点head,写一个函数把这个链表逆序 ( Intel)
答案:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "iostream"
using namespace std;
struct Node
{
int data ;
Node *next ;
};
typedef struct Node Node ;
void CreatNode(Node** head)
{
int ndata;
Node* headTmp = NULL;
Node* pM = NULL;
Node* pCur = NULL;
pCur = headTmp = (Node*)malloc(sizeof(Node));
headTmp->data = 0;
headTmp->next = NULL;
cin>>ndata;
while ( ndata != 0)
{
pM = (Node*)malloc(sizeof(Node));
pM->data = ndata;
pM->next = NULL;
pCur->next = pM;
pCur = pCur->next;
cin>>ndata;
}
*head = headTmp;
}
void ReverseList(Node *head)
{
Node* pCur = head->next->next;
Node* pLast = head->next;
while (pCur)
{
Node* p = pCur->next;
pCur->next = pLast;
pLast = pCur;
pCur = p;
}
head->next->next = NULL;
head->next = pLast;
}
void print(Node *head)
{
Node* tmp = head->next;
while (tmp)
{
cout<<tmp->data<<' ';
tmp = tmp->next;
}
}
int main()
{
Node* head = NULL;
CreatNode(&head);
print(head);
ReverseList(head);
cout<<endl;
print(head);
return 1;
}