标签:length link create main created cpp let 长度 lin
//
// main.cpp
// 单向链表的基本运算
// Created by 柯木超 on 2018/11/27.
// Copyright ? 2018 柯木超. All rights reserved.
//
#include <iostream>
typedef struct Node{
int data;
struct Node *next;
}linkNode, *link;
link createNode() {
// 先声明,然后再赋值, T记录头节点,M 记录当前移动节点,P是当前输入节点
link T,P,M;
// 1、给头节点开辟新的内存空间
T = (link)(malloc(sizeof(linkNode)));
M = T;
for (int a=0;a<10;a++) {
P = (link)(malloc(sizeof(linkNode)));
P->data = a;
P->next = NULL;
M->next = P;
M = P; //M记录当前移动节点
}
return T;
}
link insertNumber(int data,int number, link L) {
int length = 0;
// 获取当前链表长度
link m = L;
while (m->next!=NULL) {
length = length+1;
m = m->next;
}
if (number >= length){
printf("插入位置超出链表总长度");
}else {
int i = 0;
while (i < number) {
L = L->next;
i = i+1;
}
link next = L->next;
link newNode = (link)malloc(sizeof(linkNode));
newNode->data = data;
L->next = newNode; // 断开链表插入新的节点
newNode->next = next; //和新的节点重新连接
}
return L;
}
link deleteNumber(int number, link L) {
int length = 0;
// 获取当前链表长度
link m = L;
while (m->next!=NULL) {
length = length+1;
m = m->next;
}
if (number >= length){
printf("删除位置超出链表总长度");
}else {
int i = 0;
while (i < number) {
L = L->next;
i = i+1;
}
link next = L->next;
L->next = next->next;
free(next);
}
return L;
}
void printNode(link L){
while (L->next != NULL) {
L = L->next;
printf("%d", L->data);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
// 创建链表
link L;
L = createNode();
// 打印链表
printNode(L);
// 插入数据
insertNumber(100, 4, L);
// 打印链表
printNode(L);
// 删除数据
deleteNumber(4, L);
// 打印链表
printNode(L);
return 0;
}
标签:length link create main created cpp let 长度 lin
原文地址:https://www.cnblogs.com/xiaokessy/p/10024830.html