代码
#include <conio.h>
#include <stdio.h>
#include <process.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <fstream>
#include <iostream>
#define max 100
using namespace std;
#define supermax 10
typedef int SElemType;
struct SqStack
{
SElemType data[100];
int top = -1;
};
struct ListNode {
int data;
struct ListNode* next;
};
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20
typedef int Status;
typedef int SElemType;
Status visit(SElemType c)
{
printf("%d ",c);
return OK;
}
Status InitStack(SqStack *S)
{
S->top=-1;
return OK;
}
Status ClearStack(SqStack *S)
{
S->top=-1;
return OK;
}
Status StackEmpty(SqStack S)
{
if (S.top==-1)
return TRUE;
else
return FALSE;
}
int StackLength(SqStack S)
{
return S.top+1;
}
int pop(SqStack *S)
{
SElemType e;
if (S->top==-1)
return ERROR;
else
e = S->data[S->top];
S->top--;
return e;
}
Status Push(SqStack *S,SElemType e)
{
if(S->top == MAXSIZE -1)
{
return ERROR;
}
S->top++;
S->data[S->top]=e;
return OK;
}
Status StackTraverse(SqStack* S)
{
int i;
i=0;
while(i<=S->top)
{
visit(S->data[i++]);
}
printf("\n");
return OK;
}
void insertNode(struct ListNode* head, int data) {
struct ListNode* newNode = (ListNode*)malloc(sizeof(struct ListNode));
newNode->data = data;
newNode->next = NULL;
struct ListNode* p = head;
while (p->next!= NULL) {
p = p->next;
}
p->next = newNode;
}
int main(){
SqStack *s = new SqStack;
struct ListNode* head = (ListNode*)malloc(sizeof(struct ListNode));
head->data = 0;
head ->next= (ListNode*)malloc(sizeof(struct ListNode));
head->next->data = 9;
head ->next->next= (ListNode*)malloc(sizeof(struct ListNode));
head->next->next->data = 10;
head->next->next->next = NULL;
ListNode* p = head;
for(int i=0; i<3; i++){
Push(s,p->data);
p = p->next;
}
ListNode*root = (ListNode*)malloc(sizeof(ListNode));
root->next = NULL;
for(int i=0; i<3; i++){
int k = pop(s);
insertNode(root,k);
}
return 0;
}
p->next的效果是和p在同一个作用域的,当p == NULL的时候p->next是未被分配空间的,segmentationFault的具体效果就像这样
这个时候p->next是访问不了的,当然p->data也不行
解决方法:
理论上while(p!=NULL&&p->next->next!=NULL)可以规避,因为这句代码是先读取&&左边的条件,如果左边的条件也不满足的话右边的条件自然也不会被访问到,只要不访问到就不会出现段错误
头节点的作用体现在创建新的链表来储存逆置链表的时候不能将逆置的的节点放在新建头节点上,但是可以与头节点的next发生关系从而达到返回头节点的函数效果,其他的解决方法是将插入函数的返回类型返回为listNode *然后使用递归的思想在函数中直接创建头节点.(有利于void的传参处理方式)
这个例子的插入函数是插入到链表结尾的