# C语言——链表

### C语言——链表

1.首先要定义结构体作为链表的结点：

typedef struct node {
int data;
struct node * next;
} Node;


2.初始化链表：

Node * InitList() {
Node * head = (Node * )malloc(sizeof(Node));
}



3.链表的尾插法：

void CreatTail(Node *head) {
Node * r, * newNode;
int data;
scanf("%d", &data);
while (data != -1) {
newNode = (Node * )malloc(sizeof(Node));
newNode->data = data;
newNode->next = r->next;
r->next = newNode;
r = newNode;
scanf("%d", &data);
}
r->next = NULL;
}


4.链表的尾插法：

void CreatHead(Node *head) {
Node *newNode;
int data;
scanf("%d", &data);
while (data != -1) {
newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
scanf("%d", &data);
}
}


5.链表的输出

void print(Node *head) {
Node *p;
while (p) {
printf(" %d\t ", p->data);
p = p->next;
}
}


6.链表的查找

Node* FindNode(Node *head, int x) {
while (p && x >= 1) {
p = p->next;
x--;
}
if (!p) {
printf("该节点不存在");
return NULL;
}
else {
return p;
}
}


7.在指定的地方插入结点：

void Insert(Node *head, int x, int data) {

Node *pre = FindNode(head, x - 1);
if (pre == NULL) {
printf("请输入正确的插入点");
}
Node *pNew = (Node *)malloc(sizeof(Node));
pNew->data = data;
pNew->next = pre->next;
pre->next = pNew;
}


8.删除指定的结点：

void Delete(Node *head, int x) {
Node *q = pre->next;
pre->next = pre->next-next;
free(q);
}


9.销毁整个链表

void DestoryList(Node *head) {
Node *q = p;
while (p) {
p = p->next;
free(q);
q = p;
}
}


void reverseList (Node *head) {    //三指针法
}
Node *p = NULL;
Node *next ;
while (q != NULL) {
next = q->next;
q->next = p;
p = q;
q = next;
}
}

• 83
点赞
• 520
收藏
觉得还不错? 一键收藏
• 23
评论
11-07 501
03-16
10-02 1532
06-26 43
06-03 62万+
02-27 1686
01-01 1万+
09-11 3588
02-05 240
08-02 223
11-24 1万+

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。