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;
}
本文介绍了一种使用C++实现链表逆序的方法。通过定义链表节点结构,并提供创建链表、逆序链表及打印链表的功能,展示了完整的链表逆序过程。该方法适用于需要对链表进行逆序操作的应用场景。
4万+

被折叠的 条评论
为什么被折叠?



