双向链表,两端指向NULL(JAVA思路的C实现)
程序员文章站
2022-07-15 20:14:56
...
#include "stdio.h"
#include "stdlib.h"
typedef struct Node{
int data;
struct Node *pre;
struct Node *next;
}line,*pline;
line * initLine(line *head){
line *node,*rear;
int length,pos=1,data;
printf("请输入链表的长度:>");
scanf("%d",&length);
if (length<1) return NULL;
head = (line *)malloc(sizeof(line));
if(!head) return NULL;
head->pre = NULL;
head->next = NULL;
rear = head;
printf("请输入第%d个数据:>",pos++);
scanf("%d",&(head->data));
for (;pos<=length;)
{
printf("请输入第%d个数据:>",pos++);
node = (line *)malloc(sizeof(line));
if(!node) return NULL;
scanf("%d",&(node->data));
node->pre = rear;
node->next = rear->next;
rear->next = node;/*这句之前忘了,要注意*/
rear = node;
}
return head;
}
void printLine(line *head)
{
line *node;
node = head;
printf("打印链表:");
while(node){
printf("%d ",node->data);
node = node->next;
}
printf("\n");
}
line * insertLine(line *head, int data, int add){
line *insNode = (line *)malloc(sizeof(line));
line *node;
int i;
if (!insNode) return -1;
insNode->data = data;
if (add == 1){
insNode->pre = NULL;
insNode->next = head;
head = insNode;
}else{
node = head;
for (i=1; i<add-1; ++i){
node = node->next;
}
if (node == NULL) {
printf("#The insert number is out of the sequence bound!\n\
#please check out the insert number.\n");
return head;
}
insNode->pre = node;
insNode->next = node->next;
if(node->next != NULL)
node->next->pre = insNode;
node->next = insNode;
}
return head;
}
line * deleteLine(line *head, int data){
line *node;
node = head;
for (;node != NULL;){
if (node->data == data){
node->pre->next = node->next;
node->next->pre = node->pre;
free(node);
node = NULL;
printf("=====节点删除完毕=====\n");
return head;
}
node = node->next;
}
printf("=====哎呦喂!没有您要删除的节点~内!=====\n");
return head;
}
int main(){
line *L = initLine(L);/*这句返回值赋值给自己是关键,java这类无指针语言的思路,要利用返回值*/
L = insertLine(L,30,7);
L = insertLine(L,15,2);
printLine(L);
L = deleteLine(L,30);
L = deleteLine(L,15);
printLine(L);
return 0;
}
输入:5 1 2 3 4 5
输出结果:
请输入链表的长度:>5
请输入第1个数据:>1
请输入第2个数据:>2
请输入第3个数据:>3
请输入第4个数据:>4
请输入第5个数据:>5
#The insert number is out of the sequence bound!
#please check out the insert number.
打印链表:1 15 2 3 4 5
=====哎呦喂!没有您要删除的节点~内!=====
=====节点删除完毕=====
打印链表:1 2 3 4 5