,单链表面试题几乎是面试的必考之题;
,对于单链表从头到尾打印与单链表的逆置不是一回事。
,单链表的从头到尾打印是打印出链表的数据。(即数据是从尾向前输出),
,,
一、单链表从头到尾打印:
/* * *,,struct ListNode  { *,,,,,,,,int val; *,,,,,,,,struct ListNode *下; *,,,,,,,,ListNode (int x),: *,,,,,,,,,,,,,,瓦尔(x),下一个(NULL), { *,,,,,,,,} *,,}; */class Solution  { 公众: ,,,vector, printListFromTailToHead (struct ListNode *,头),{ ,,,,,,,,vector ,结果; ,,,,,,,,stack<, ListNode *祝辞,节点; ,,,,,,,,,,,,struct ListNode *, newhead=头; ,,,,,,,,,,,,,(newhead !=NULL) ,,,,,,,,,,,,{ ,,,,,,,,,,,,node.push (newhead); ,,,,,,,,,,,,newhead=newhead→下; ,,,,,,,,} ,,,,,,,,(! node.empty ()) ,,,,,,,,,,,{ ,,,,,,,,,,,newhead=node.top (); ,,,,,,,,,,,result.push_back (newhead→val); ,,,,,,,,,,,node.pop (); ,,,,,,,} ,,,,,,,return 结果; ,,,} ,,,,,,,, };
二,单链表的逆置
/* struct ListNode  { ,,,int val; ,,,struct ListNode *下; ,,,ListNode (int x),: ,,,,,,,,,,,瓦尔(x),下一个(NULL), { ,,,} };*/class Solution  { 公众: ,,,ListNode *, ReverseList (ListNode *, pHead), { ,,,,,,,,,,,,如果(pHead==NULL) ,,,,,,,,,,,,,,,,return 零; ,,,,,,,,,,ListNode *,坏蛋=pHead; ,,,,,,,,,,ListNode *, newHead=零; ,,,,,,,,(坏蛋) ,,,,,,,,,,,{ ,,,,,,,,,,,ListNode *, tmp=坏蛋; ,,,,,,,,,,,坏蛋=cur→下; ,,,,,,,,,,,tmp→下=newHead; ,,,,,,,,,,,newHead=tmp; ,,,,,,,} ,,,,,,,return newHead; ,,,,,,,,,,, ,,,} };