|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
×
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
struct Node* prev;
struct Node* next;
};
void insertBefore(struct Node* head,int i,int x)
{
if(i<=0)
{
printf("插入位置无效\n");
return;
}
struct Node* current=head;
int currentPosition=0;
while(current!=NULL&¤tPosition<i)
{
current=current->next;
currentPosition++;
}
if(currentPosition!=i||current==NULL)
{
printf("插入位置无效\n");
return;
}
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=x;
newNode->prev=current->prev;
newNode->next=current;
current->prev->next=newNode;
current->prev=newNode;
}
int main()
{
struct Node* head=(struct Node*)malloc(sizeof(struct Node));
head->prev=NULL;
head->next=NULL;
int values[]={10,20,30};
for(int i=3;i>=0;i--)
{
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=values[i];
newNode->prev=head;
newNode->next=head->next;
if(head->next!=NULL)
{
head->next->prev=newNode;
}
head->next=newNode;
}
insertBefore(head,2,15);
struct Node* current=head->next;
while(current!=NULL)
{
printf("%3d",current->data);
current=current->next;
}
current=head->next;
while(current!=NULL)
{
struct Node* temp=current;
current=current->next;
free(temp);
}
free(head);
return 0;
}
为什么输出结果是10 15 20 30 0,0是从哪来的? |
|