解决这个问题其实有很多种思路,例如:
第一种:使用递归配合回溯即刻实现。
第二种:利用栈的特性,将链表循环遍历放入栈中,栈顶是链表的尾结点,然后出栈依次打印就可从尾到头打印链表。
第三种:使用双向链表,加上一个指针即指向前驱结点,这样也可以实现。
第四种:把链表中连接结点的指针反转过来,改变链表的方向,再从头都尾打印即可。
解决方法很多种,我们在这里给出第一二种的具体实现步骤。
struct ListNode {
int m_nValue;
struct ListNode *m_pNext;
};
struct LinkStack {
int *pBase;
int *pTop;
int stackSize;
};
struct ListNode * creatListNode(int count) {
struct ListNode *p = NULL;
while (count>0) {
struct ListNode *head = malloc(sizeof(struct ListNode));
head->m_pNext = p;
head->m_nValue = count;
p = head;
count--;
}
return p;
}
第一种方式
void initStack (struct LinkStack *s) {
s->pBase = malloc(sizeof(int *));
if (!s->pBase) {
return;
}
s->pTop = s->pBase;
s->stackSize = 100;
}
void displayStack (struct ListNode *pHead,struct LinkStack *linkS) {
while (pHead != NULL) {
*(++linkS->pTop) = pHead ->m_nValue;
pHead = pHead->m_pNext;
}
while (linkS->pBase != linkS->pTop) {
int *top = linkS->pTop--;
NSLog(@"%d",*top);
}
}
//第二种方式
void displayRecursion(struct ListNode * pHead){
if (pHead == NULL) {
return;
}
struct ListNode * p = pHead->m_pNext;
displayRecursion(p);
printf("%d",pHead->m_nValue);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
struct ListNode * pHead = creatListNode(3);
struct LinkStack * linkS = malloc(sizeof(struct LinkStack));
initStack(linkS);
// displayStack(pHead,linkS);
displayRecursion(pHead);
test();
}
return 0;
}
插入一下栈溢出的问题,值得思考:
int a = 10000000;
void test() {
if (a==0) {
return;
}
a--;
test();
}