上篇博文中讨论了链表的一些基本操作:

然而,为创建一个多功能的链表,在深度学习之前我们还需要了解更多的链表操作。

  • 在表头插入元素。
  • 在表中插入元素。
    • 在确定的位置插入。
    • 在某个元素的后面插入。
  • 从链表中删除一个元素。
  • 删除整个链表。

在链表头部插入元素

为了在链表头部插入元素,我们要完成一项小任务:创建一个临时节点,把数据存入这个临时节点,将这个节点指向链表的头节点。

/*
Defining a function to add an element at the beginning of the Linked List
*/
struct node * addAtBeg(struct node * head, int number)
{
//making a temporary node
struct node * temp = (struct node*)malloc(sizeof(struct node)); //assigning the necessary values
temp -> data = number;
temp -> next = head; //we make the new node as the head node and return
return temp;
}

在链表的特定位置插入数据

依然创建临时节点,把要插入的数据存入这个节点。将临时节点指向指定位置(假定指定位置在两个节点中间)的下个节点,把指定位置上个节点指向临时节点。

/*Defining a function to add at a particular position in a Linked List*/
struct node * addAtPos(struct node *head, int number, int pos)
{
//this is our initial position
int initial_pos = ; //This is a very important statement in all Linked List traversals
//Always create some temporary variable to traverse the list.
//This is done so that we do not loose the starting point of the
//Linked List, that is the HEAD
struct node * mover = head; while(initial_pos != pos)
{
//we need to traverse the Linked List, until
//we reached the userdefined position
mover = mover -> next; //incrementing initial position
initial_pos++;
} //Now mover points to the user defined position //Create a temporary node
struct node * temp = (struct node*)malloc(sizeof(struct node));
temp -> data = number; //Inserting the node.
temp -> next = mover -> next;
mover -> next = temp; return head;
}

在指定节点后插入数据

整个过程其实和上面的一样,唯一的区别是我们需要遍历整个链表找到指定节点,然后执行过程大同小异。

/*
Defining a function to insert after a specified node
*/
struct node * addAfterNode(struct node * head, int number, int after_num)
{
//creating a temporary node to iterate
struct node * mover = head; while(mover -> data != after_num)
{
// We need to iterate until we reach the desired node
mover = mover -> next;
} //Now mover points at the node that we want to insert struct node *temp = (struct node*)malloc(sizeof(struct node));
temp -> data = number;
temp -> next = mover -> next;
mover -> next = temp; return head;
}

删除节点

删除节点,我们需要遍历链表找到要删除的节点。删除节点不需要什么高级的操作,只要将被删除节点的前个节点的next指向被删除节点的下个节点就完成了。

/*
Defining a function to delete a node in the Linked List
*/
struct node * deleteANode(struct node * head, int node_data)
{
//In this function we will try to delete a node that
//has the particular node data given by the user struct node * mover = head; //Creating a variable to store the previous node
struct node * prev; while(mover -> data != node_data)
{
prev = mover;
mover = mover -> next;
} //Now mover point to the node that we need to delete
//prev points to the node just before mover. //Deleting the node mover
prev -> next = mover -> next; return head;
}

删除整个链表

简单清空HEAD就能删除整个链表,但数据仍然在内存中,只是丢失对它的连接。要彻底删除我们可以用free()函数。

/*
Defining a function to delete the entire List
*/
struct node * deleteList(struct node * head)
{
struct node * temp; while(head != NULL)
{
temp = head;
head = head -> next;
free(temp);
} return NULL;
}

完整代码如下:

#include<stdio.h>
#include<stdlib.h> //creating the basic structure of a node of a Linked List
struct node
{
int data;
struct node * next;
}; /*
Code obtained from http://www.studyalgorithms.com
*/
/* Defining a function to create a new list.
The return type of the function is struct node, because we will return the head node
The parameters will be the node, passed from the main function.
The second parameter will be the data element.
*/
struct node * createList(struct node *head,int number)
{
//creating a temporary node for our initialization purpose //the below line allocates a space in memory that can hold the data in a node.
struct node *temp = (struct node *)malloc(sizeof(struct node)); //assigning the number to data
temp -> data = number; //assigning the next of this node to NULL, as a new list is formed.
temp -> next = NULL; //now since we have passed head as the parameter, we need to return it.
head = temp;
return head;
} /*
Defining a case when we need to element in the Linked List.
Here 2 cases can arise:-
-The Linked List can be empty, then we need to create a new list
-The Linked List exists, we need to add the element
*/
struct node * addElement(struct node *head, int number)
{
if(head == NULL)
head = createList(head, number); // we can directly call the above function
else
{
// now this is a case when we need to add an element to an existing list. //Creating a new node and assigning values
struct node * temp = (struct node*)malloc(sizeof(struct node));
temp -> data = number;
temp -> next = NULL; //Now we have created the node but, we need to insert it at the right place.
//A Linked List terminates when we encounter a NULL
//Feel free to copy but please acknowledge studyalgorithms.com
//Let us traverse the List using another temporary variable.
//We will point it to the start
struct node * temp2 = head; //The limiting condition of the while loop "until temp2's NEXT is not equal to NULL
//This will happen only in case of the last node of the list.
while(temp2 -> next != NULL)
{
// We need to go to the next node
temp2 = temp2 -> next;
} //Now temp2 points at the last node of the list.
//We can add the node at this position now. temp2 -> next = temp; // the number is added to the end of the List.
} return head; // because we only need the HEAD pointer for a Linked List.
} /*
A function to print the Linked List.
The return type of this function will be void, as we do not need to return anything.
We just need the HEAD as the parameter, to traverse the Linked List.
*/
void printList(struct node * head)
{
printf("\nThe list is as:- \n");
// The terminating point of a Linked List is defined when we encounter a NULL
while(head != NULL)
{
printf("%d ",head->data); //now we need to move to the next element
head = head->next;
//Feel free to copy but please acknowledge studyalgorithms.com
}
printf("\n");
} /*
Defining a function to add an element at the beginning of the Linked List
*/
struct node * addAtBeg(struct node * head, int number)
{
//making a temporary node
struct node * temp = (struct node*)malloc(sizeof(struct node)); //assigning the necessary values
temp -> data = number;
temp -> next = head; //we make the new node as the head node and return
return temp;
} /*Defining a function to add at a particular position in a Linked List*/
struct node * addAtPos(struct node *head, int number, int pos)
{
if(head == NULL)
{
printf("\nList is EMPTY");
return NULL;
}
//this is our initial position
int initial_pos = ; //This is a very important statement in all Linked List traversals
//Always create some temporary variable to traverse the list.
//This is done so that we do not loose the starting point of the
//Linked List, that is the HEAD
struct node * mover = head; while(initial_pos != pos)
{
//we need to traverse the Linked List, until
//we reached the userdefined position
mover = mover -> next; //incrementing initial position
initial_pos++;
//Feel free to copy but please acknowledge studyalgorithms.com
} //Now mover points to the user defined position //Create a temporary node
struct node * temp = (struct node*)malloc(sizeof(struct node));
temp -> data = number; //Inserting the node.
temp -> next = mover -> next;
mover -> next = temp; return head;
} /*
Defining a function to insert after a specified node
*/
struct node * addAfterNode(struct node * head, int number, int after_num)
{
if(head == NULL)
{
printf("\nList is EMPTY");
return NULL;
} //creating a temporary node to iterate
struct node * mover = head; while(mover -> data != after_num)
{
// We need to iterate until we reach the desired node
mover = mover -> next;
} //Now mover points at the node that we want to insert struct node *temp = (struct node*)malloc(sizeof(struct node));
temp -> data = number;
temp -> next = mover -> next;
//Feel free to copy but please acknowledge studyalgorithms.com
mover -> next = temp; return head;
} /*
Defining a function to delete a node in the Linked List
*/
struct node * deleteANode(struct node * head, int node_data)
{
if(head == NULL)
{
printf("\nList is EMPTY");
return NULL;
} //In this function we will try to delete a node that
//has the particular node data given by the user struct node * mover = head; //Creating a variable to store the previous node
struct node * prev; while(mover -> data != node_data)
{
prev = mover;
mover = mover -> next;
} //Now mover point to the node that we need to delete
//prev points to the node just before mover. //Deleting the node mover
prev -> next = mover -> next; return head;
} /*
Defining a function to delete the entire List
*/
struct node * deleteList(struct node * head)
{
if(head == NULL)
{
printf("\nList is EMPTY");
return NULL;
} struct node * temp; while(head != NULL)
{
temp = head;
head = head -> next;
free(temp);
} return NULL;
} //Defining the main function to implement all the above defined functions
int main(void)
{
int choice = ;
int flag = ;
int num;
int pos; struct node *listHead = NULL; while(flag != )
{
printf("\nWhat do you want to do?\n1.>Create a List\n2.>Add an element at the end\n3.>Add an element at the beginning\n4.>Add an element at a position\n5.>Add an element after a certain element\n6.>Delete at node.\n7.>Print the List\n8.>Delet the List\n9.>Exit.\n\nEnter choice:- ");
scanf("%d",&choice); switch(choice)
{
case :
printf("Enter a number:- ");
scanf("%d",&num);
listHead = createList(listHead, num);
//Feel free to copy but please acknowledge studyalgorithms.com
printList(listHead);
break; case :
printf("Enter a number:- ");
scanf("%d",&num);
listHead = addElement(listHead, num);
printList(listHead);
break; case :
printf("Enter a number:- ");
scanf("%d",&num);
listHead = addAtBeg(listHead, num);
printList(listHead);
break; case :
printf("Enter a number:- ");
scanf("%d",&num);
printf("Enter a position:- ");
scanf("%d",&pos);
listHead = addAtPos(listHead, num, pos);
printList(listHead);
break; case :
printf("Enter a number:- ");
scanf("%d",&num);
printf("Enter a node:- ");
scanf("%d",&pos);
listHead = addAfterNode(listHead, num, pos);
printList(listHead);
break; case :
printf("Enter a node to delete:- ");
scanf("%d",&num);
listHead = deleteANode(listHead, num);
printList(listHead);
break; case :
printList(listHead);
break; case :
listHead = deleteList(listHead);
break; case :
flag = ;
break; default:
printf("Invalid choice\n");
//Feel free to copy but please acknowledge studyalgorithms.com
break;
}
} return ;
}

关于链表的一些重要操作(Important operations on a Linked List)的更多相关文章

  1. 链表的基本操作(Basic Operations on a Linked List)

    链表可以进行如下操作: 创建新链表 增加新元素 遍历链表 打印链表 下面定义了对应以上操作的基本函数. 创建新链表 新链表创建之后里面并没有任何元素,我们要为数据在内存中分配节点,再将节点插入链表.由 ...

  2. 数据结构之链表-链表实现及常用操作(C++篇)

    数据结构之链表-链表实现及常用操作(C++篇) 0.摘要 定义 插入节点(单向链表) 删除节点(单向链表) 反向遍历链表 找出中间节点 找出倒数第k个节点 翻转链表 判断两个链表是否相交,并返回相交点 ...

  3. 链表的无锁操作 (JAVA)

    看了下网上关于链表的无锁操作,写的不清楚,遂自己整理一部分,主要使用concurrent并发包的CAS操作. 1. 链表尾部插入 待插入的节点为:cur 尾节点:pred 基本插入方法: do{ pr ...

  4. 【线性代数】2-4:矩阵操作(Matrix Operations)

    title: [线性代数]2-4:矩阵操作(Matrix Operations) toc: true categories: Mathematic Linear Algebra date: 2017- ...

  5. C++实现链表的相关基础操作

    链表的相关基础操作 # include <iostream> using namespace std; typedef struct LNode { int data; //结点的数据域 ...

  6. C++中单链表的建立和操作

    准备数据 准备在链表操作中需要用到的变量及数据结构 示例代码如下: struct Data //数据结点类型 { string key; //关键字 string name; int age; }; ...

  7. C语言描述链表的实现及操作

    一.链表的创建操作 // 操作系统 win 8.1 // 编译环境 Visual Stuido 2017 #include<stdio.h> #include<malloc.h> ...

  8. 5.List链表类型介绍和操作

    数据类型List链表 (1)介绍 list类型其实就是一个双向链表.通过push,pop操作从链表的头部或者尾部添加删除元素.这使得list既可以用作栈,也可以用作队列. 该list链表类型应用场景: ...

  9. C++学习---单链表的构建及操作

    #include <iostream> using namespace std; typedef struct LinkNode { int elem;//节点中的数据 struct Li ...

随机推荐

  1. <php>json小结

    1.页面中如果即用到jquery包,又用到js文件,要先写jquery包,再加载js文件 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Tr ...

  2. Git实现从本地加入项目到远程仓库

    Git是如今最流行的版本号控制系统之中的一个了,今天也试试了.成功了上传了远程仓库,接下来看看我是怎么做的. 1.首先,要有git的账号.点击查看怎么注冊? 2.注冊成功之后.登陆GitHub.然后, ...

  3. C/C++笔试准备(2)

    问题:编辑距离,是指将一个字符串变为另一个字符串,仅可以3种操作:修改一个字符,删除一个字符,插入一个字符.the变成that:删除e,插入a,插入t.20’ 实现编辑距离算法. 解算:利用动态规划的 ...

  4. C语言随记-1

    涉及指针.数组.函数指针 几种声明形式 int *a[5]; // a是一个有5个元素的数组,每个元素是整数类型指针(int *) int *a[] = {0x100, 0x104, 0x108, 0 ...

  5. linux提取指定行至指定位置

    grep查找ERROR,定位位置 awk打印到指定行数 sed打印到文本末尾 awk打印到文本末尾 方法一 #!/bin/csh -f if(-f errorlog.rpt) then rm -rf ...

  6. oracle之substr函数

    substr(字符串,截取开始位置,截取长度) //返回截取的字 substr(,) //返回结果为 'H' *从字符串第一个字符开始截取长度为1的字符串 substr(,) //返回结果为 'H' ...

  7. vsftp虚拟用户登录配置详解

    一.安装:1.安装Vsftpd服务:# yum install vsftpd 2.安装DB4部件包:这里要特别安装一个db4的包,用来支持文件数据库.# yum install db4-utils 二 ...

  8. Javascript高级程序设计读书笔记(第六章)

    第6章  面向对象的程序设计 6.2 创建对象 创建某个类的实例,必须使用new操作符调用构造函数会经历以下四个步骤: 创建一个新对象: 将构造函数的作用域赋给新对象: 执行构造函数中的代码: 返回新 ...

  9. 可用与禁用 E:enabled { sRules }

    <!DOCTYPE html><html lang="zh-cmn-Hans"><head><meta charset="utf ...

  10. Tomcat 7.0 进入项目管理页面时的密码问题

    tomcat7 这个版本,官方网下载的原始包项目管理页面的权限和之前版本的配置有点区别. 到Tomcat的conf文件夹下找到tomcat-users.xml文件,有配置权限的配置文件.     ma ...