[数据结构]单链表逆置

#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");  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值