#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
typedef struct tagListNode{
int nData;
struct tagListNode* s_pNext;
}ListNode, *pListNode;
void PrintList(pListNode head);
pListNode ReverseList(pListNode head);
int main()
{
//分配链表头结点
ListNode *s_pHead;
s_pHead = (ListNode*)malloc(sizeof(ListNode));
s_pHead->s_pNext = NULL;
s_pHead->nData = 0;
//将[1,9]加入链表
int i;
ListNode *s_pNode1, *s_pNode2;
s_pNode1 = s_pHead;
for(i = 1; i < 10; i++)
{
s_pNode2 = (ListNode *)malloc(sizeof(ListNode));
s_pNode2->nData = i;
s_pNode2->s_pNext = NULL;
s_pNode1->s_pNext = s_pNode2;
s_pNode1 = s_pNode2;
}
//
// 输出链表
//
PrintList(s_pHead);
//
// 逆序链表
//
s_pHead = ReverseList(s_pHead);
//
// 输出链表
//
PrintList(s_pHead);
return 0;
}
pListNode ReverseList(pListNode s_pHead)
{
//
// 入参检测
//
if(s_pHead == NULL || s_pHead->s_pNext == NULL)
{
return s_pHead;
}
ListNode *s_pTempNode = NULL,
*s_pNode1 = s_pHead,
*s_pNode2 = s_pHead->s_pNext;
while(s_pNode2 != NULL)
{
s_pTempNode = s_pNode2->s_pNext;
s_pNode2->s_pNext = s_pNode1;
s_pNode1 = s_pNode2;
s_pNode2 = s_pTempNode;
}
// 设置链表尾
s_pHead->s_pNext = NULL;
return s_pNode1;
}
void PrintList(pListNode s_pHead)
{
ListNode* p = s_pHead;
while(p != NULL)
{
printf("%d ", p->nData);
p = p->s_pNext;
}
printf("\n");
}
[数据结构]单链表逆置
最新推荐文章于 2024-08-27 12:51:30 发布