思路:利用递归方式从尾到头打印



#define
_CRT_SECURE_NO_WARNINGS
1



//从尾到头打印单链表

#include
<iostream>


using
namespace
std;





typedef
int
DataType
;


typedef
struct
SListNode


{



DataType
data;
//数据



struct
SListNode
* next;
//指向下一个结点的指针


}
SListNode
;





SListNode
* CreateNode(
DataType
x
)
//创造结点


{



//1.先开辟空间 2.数据赋给data 3.指针置空



SListNode
* NewNode = (
SListNode
*)malloc(
sizeof
(
SListNode
));


NewNode->data =
x
;


NewNode->next =
NULL
;






return
NewNode;


}





void
PushBack(
SListNode
* &
ppHead
,
int
Data
)


{



//1.none 2.one and more



if
(
ppHead
==
NULL
)


{



ppHead
= CreateNode(
Data
);


}



else


{



//1.先找到尾结点 2.把新节点链起来



SListNode
* cur =
ppHead
;



while
(cur->next)


{


cur = cur->next;


}

cur->next = CreateNode(
Data
);


}


}





//从尾到头打印


void
PrintList(
SListNode
* &
ppHead
)


{



if
(
ppHead
==
NULL
)



//cout << "NULL";



return
;



else


{



//递归打印


PrintList(
ppHead
->next);


cout <<
ppHead
->data <<
" "
;


}





}





void
Test()


{



SListNode
* pHead =
NULL
;


PushBack(pHead, 1);


PushBack(pHead, 2);


PushBack(pHead, 3);


PushBack(pHead, 4);


PushBack(pHead, 5);


PrintList(pHead);

}

int
main()


{


Test();


system(
"pause"
);



return
0;

}



链表面试题--从尾到头打印单链表_结点