您的位置:首页 > 其它

双向链表 删除某个节点

2016-05-05 09:36 288 查看
#include<iostream>
using namespace std;

typedef struct Node
{
int value;
struct Node *prev;
struct Node *next;
}*Linklist, Node;

Linklist CreateList(Linklist &L,int n)
{
int i;
Linklist s,h;
L = (Linklist)malloc(sizeof(Node));
h = L;
scanf("%d",&L->value);
L->prev = NULL;
L->next = NULL;
for(i=1;i<n;i++)
{
s = (Linklist)malloc(sizeof(Node));
scanf("%d",&s->value);
L->next = s;
s->prev = L;
L = s;
}
//  printf("aaaa   %d\n",h->next->value);
s->next = NULL;
return h;
}

int cal_len(Linklist head)
{
int count=1;
Linklist temp1 = head;
while(temp1->next != NULL)
{
temp1 = temp1->next;
count++;

}
return count;
}

Linklist remove_list_node(Linklist &head,int index)
{
Linklist temp;
Linklist temp1;
Linklist head_temp;
int i;
temp = head;
head_temp = head;
if(index == 0)
{
head->next->prev=NULL;
head = head->next;
temp->next = NULL;
return head;
//      printf("temp->value=%d,head->value=%d\n",temp->value,head->value);
//      printf("%d\n",temp->value);
}
else if(index == cal_len(head)-1)
{
for(i=0;i<index-1;i++)
{
head = head->next;
}
temp1 = head->next;
head->next->prev = NULL;
head->next = NULL;
return head_temp;
//      printf("%d\n",temp1->value);
}
else
{
for(i=0;i<index-1;i++)
{
head = head->next;
}
temp1 = head->next;
head->next->next->prev = head;
head->next = head->next->next;
return head_temp;
//      printf("%d\n",temp1->value);
}
}

int main()
{
Linklist L,head,head_temp1;
int n,index;
int i;
scanf("%d",&n);  //个数
scanf("%d",&index);  //要删除的数的下表(从0开始)
//  int head_temp1;
head = CreateList(L,n);
//  printf("%d\n",cal_len(head));

head_temp1 = remove_list_node(head,index);
for(i=0;i<n-1;i++)
{
printf("%d\n",head_temp1->value);
head_temp1 = head_temp1->next;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: