1、定义节点
typedef struct Node
{
int data;
struct Node* pNext;
}NODE, *PNODE;
2、创建链表
PNODE create_list()
{
int len;
int i;
int val;
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if(pHead == NULL)
return 0;
PNODE pTail = pHead;
pTail->pNext = NULL;
cout<<"请输入您要生成的链表的个数:";
cin>>len;
for(i = 0; i < len; i++)
{
cout<<"请输入第"<<i+1<<"个节点的值:";
cin>>val;
PNODE pNew = (PNODE)malloc(sizeof(NODE));
pNew->data = val;
pTail->pNext = pNew;
pNew->pNext = NULL;
pTail = pNew;
}
return pHead;
}
3、遍历链表
void traverse_list(PNODE pHead)
{
PNODE p = pHead->pNext;
while(p != NULL)
{
cout<<p->data<<' ';
p = p->pNext;
}
}
void traverse1_list(PNODE pHead)
{
PNODE p = pHead;
while(p != NULL)
{
cout<<p->data<<' ';
p = p->pNext;
}
}
4、反转链表
PNODE ReverseList(PNODE pHead)
{
// 如果链表为空或只有一个结点,无需反转,直接返回原链表头指针
if(pHead == NULL || pHead->pNext == NULL)
return pHead;
PNODE pReversedHead = NULL; //反转后链表的头结点,初始化为NULL
PNODE pCurrent = pHead; //定义pCurrent指向链表中头结点
while(pCurrent != NULL)
{
PNODE pTemp = pCurrent;
pCurrent = pCurrent->pNext;
pTemp->pNext = pReversedHead; //把pRverseHead定位为反转后链表的头结点,
pReversedHead = pTemp; //把头结点放在ptemp位置.
}
return pReversedHead;
}
5、main
int main()
{
PNODE pHead = NULL;
pHead = create_list();
traverse_list(pHead);
cout<<endl;
PNODE p = NULL;
p = ReverseList(pHead->pNext);
traverse1_list(p);
cout<<endl;
return 0;
}
6、运行结果