文章目录
1、输入数字建立链表
代码:
#include<stdio.h>
#include<stdlib.h>
typedef struct ListNode {
int data;
struct ListNode *next;
}*PT_ListNode, T_ListNode;
//输入数字建立链表
int main() {
T_ListNode *head, *tail, *p, *r, *q;
/* 建立虚拟头结点 */
head = (PT_ListNode)malloc(sizeof(T_ListNode));
head->next = NULL;
tail = head;
/* 尾插法建立链表 */
char s;
do {
int k;
scanf("%d", &k);
tail->next = (PT_ListNode)malloc(sizeof(T_ListNode));
tail->next->data = k;
tail->next->next = NULL;
tail = tail->next;
} while ((s = getchar()) != '\n');
//获取要删除的节点
int m;
scanf("%d", &m);
//接下来是删除操作
p = head;
while(p->next != NULL) {
r = p;
p = p->next;
if(p->data == m) {
r->next = p->next;
free(p);
p = NULL;
break;
}
}
//打印删除后的链表
q = head->next;
while (q != NULL) {
printf("%d ", q->data);
q = q->next;
}
return 0;
}
输出:
gcc test1.c -o test1.exe
.\test1.exe
1 2 3
1
2 3
2、输入字符建立链表
代码:
#include<stdio.h>
#include<stdlib.h>
//单链表结构体
typedef struct ListNode {
int data;
struct ListNode *next;
}*PT_ListNode, T_ListNode;
//输入字符建立链表
int main() {
T_ListNode *head, *tail, *p, *r, *q;
/* 建立虚拟头结点 */
head = (PT_ListNode)malloc(sizeof(T_ListNode));
head->next = NULL;
tail = head;
/* 尾插法建立链表 */
char s;
while ((s = getchar()) != '\n') {
int num = 0;
num = num * 10 + s - '0';
while ((s = getchar()) != ' ' && s != '\n') {
num = num * 10 + s - '0';
}
tail->next = (PT_ListNode)malloc(sizeof(T_ListNode));
tail->next->data = num;
tail->next->next = NULL;
tail = tail->next;
if (s == '\n') {
break;
}
}
//输入删除的节点
int delNode = 0;
while ((s = getchar()) != ' ' && s != '\n') {
delNode = delNode * 10 + s - '0';
}
//删除节点
p = head;
while(p->next != NULL) {
r = p;
p = p->next;
if(p->data == delNode) {
r->next = p->next;
free(p);
p = NULL;
break;
}
}
//打印删除后的链表
q = head->next;
while (q != NULL) {
printf("%d ", q->data);
q = q->next;
}
return 0;
}
输出:
gcc test.c -o test.exe
.\test.exe
33 44 556
33
44 556