原文: https://www.programiz.com/dsa/linked-list-operations

在本教程中,您将学习链表上的不同操作。 此外,您还将发现 C/C++ ,Python 和 Java 中链表操作的实现。

现在您已经了解了链表和它们的类型的基本概念,是时候深入了解可以执行的常见操作了。

请记住两个要点:

  • head指向链表的第一个节点
  • 最后一个节点的next指针是NULL,因此,如果下一个当前节点是NULL,我们已经到达链表的末尾。

在所有示例中,我们将假定链表具有三个节点1 --->2 --->3,其节点结构如下:

  1. struct node
  2. {
  3. int data;
  4. struct node *next;
  5. };

如何遍历链表

显示链表的内容非常简单。 我们继续将临时节点移至下一个节点并显示其内容。

tempNULL时,我们知道我们已经到达链表的末尾,因此我们退出了while循环。

  1. struct node *temp = head;
  2. printf("\n\nList elements are - \n");
  3. while(temp != NULL)
  4. {
  5. printf("%d --->",temp->data);
  6. temp = temp->next;
  7. }

该程序的输出为:

  1. List elements are -
  2. 1 --->2 --->3 --->

如何将元素添加到链表

您可以将元素添加到链表的开始,中间或结尾。

添加到开头

  • 为新节点分配内存
  • 存储数据
  • 更改新节点的next指向head
  • head更改为指向最近创建的节点
  1. struct node *newNode;
  2. newNode = malloc(sizeof(struct node));
  3. newNode->data = 4;
  4. newNode->next = head;
  5. head = newNode;

添加到最后

  • 为新节点分配内存
  • 存储数据
  • 遍历到最后一个节点
  • 将最后一个节点的next更改为最近创建的节点
  1. struct node *newNode;
  2. newNode = malloc(sizeof(struct node));
  3. newNode->data = 4;
  4. newNode->next = NULL;
  5. struct node *temp = head;
  6. while(temp->next != NULL){
  7. temp = temp->next;
  8. }
  9. temp->next = newNode;

添加到中间

  • 分配内存并存储新节点的数据
  • 遍历到新节点所需位置之前的节点
  • 更改next指针以在其间包含新节点
  1. struct node *newNode;
  2. newNode = malloc(sizeof(struct node));
  3. newNode->data = 4;
  4. struct node *temp = head;
  5. for(int i=2; i < position; i++) {
  6. if(temp->next != NULL) {
  7. temp = temp->next;
  8. }
  9. }
  10. newNode->next = temp->next;
  11. temp->next = newNode;

如何从链表中删除

您可以从开头,结尾或特定位置删除。

从头删除

  • head指向第二个节点
  1. head = head->next;

从结尾删除

  • 遍历到倒数第二个元素
  • 将其next指针更改为null
  1. struct node* temp = head;
  2. while(temp->next->next!=NULL){
  3. temp = temp->next;
  4. }
  5. temp->next = NULL;

从中间删除

  • 遍历到要删除的元素之前的元素
  • 更改next指针以将节点从链中排除
  1. for(int i=2; i< position; i++) {
  2. if(temp->next!=NULL) {
  3. temp = temp->next;
  4. }
  5. }
  6. temp->next = temp->next->next;

完整的链表操作程序

  1. # Linked list operations in Python
  2. # Create a node
  3. class Node:
  4. def __init__(self, item):
  5. self.item = item
  6. self.next = None
  7. class LinkedList:
  8. def __init__(self):
  9. self.head = None
  10. # Insert at the beginning
  11. def insertAtBeginning(self, data):
  12. new_node = Node(data)
  13. new_node.next = self.head
  14. self.head = new_node
  15. # Insert after a node
  16. def insertAfter(self, node, data):
  17. if node is None:
  18. print("The given previous node must inLinkedList.")
  19. return
  20. new_node = Node(data)
  21. new_node.next = node.next
  22. node.next = new_node
  23. # Insert at the end
  24. def insertAtEnd(self, data):
  25. new_node = Node(data)
  26. if self.head is None:
  27. self.head = new_node
  28. return
  29. last = self.head
  30. while (last.next):
  31. last = last.next
  32. last.next = new_node
  33. # Deleting a node
  34. def deleteNode(self, position):
  35. if self.head == None:
  36. return
  37. temp_node = self.head
  38. if position == 0:
  39. self.head = temp_node.next
  40. temp_node = None
  41. return
  42. # Find the key to be deleted
  43. for i in range(position - 1):
  44. temp_node = temp_node.next
  45. if temp_node is None:
  46. break
  47. # If the key is not present
  48. if temp_node is None:
  49. return
  50. if temp_node.next is None:
  51. return
  52. next = temp_node.next.next
  53. temp_node.next = None
  54. temp_node.next = next
  55. def printList(self):
  56. temp_node = self.head
  57. while (temp_node):
  58. print(str(temp_node.item) + " ", end="")
  59. temp_node = temp_node.next
  60. if __name__ == '__main__':
  61. llist = LinkedList()
  62. llist.insertAtEnd(1)
  63. llist.insertAtBeginning(2)
  64. llist.insertAtBeginning(3)
  65. llist.insertAtEnd(4)
  66. llist.insertAfter(llist.head.next, 5)
  67. print('Linked list:')
  68. llist.printList()
  69. print("\nAfter deleting an element:")
  70. llist.deleteNode(3)
  71. llist.printList()
  1. // Linked list operations in Java
  2. class LinkedList {
  3. Node head;
  4. // Create a node
  5. class Node {
  6. int item;
  7. Node next;
  8. Node(int d) {
  9. item = d;
  10. next = null;
  11. }
  12. }
  13. public void insertAtBeginning(int data) {
  14. // insert the item
  15. Node new_node = new Node(data);
  16. new_node.next = head;
  17. head = new_node;
  18. }
  19. public void insertAfter(Node prev_node, int data) {
  20. if (prev_node == null) {
  21. System.out.println("The given previous node cannot be null");
  22. return;
  23. }
  24. Node new_node = new Node(data);
  25. new_node.next = prev_node.next;
  26. prev_node.next = new_node;
  27. }
  28. public void insertAtEnd(int data) {
  29. Node new_node = new Node(data);
  30. if (head == null) {
  31. head = new Node(data);
  32. return;
  33. }
  34. new_node.next = null;
  35. Node last = head;
  36. while (last.next != null)
  37. last = last.next;
  38. last.next = new_node;
  39. return;
  40. }
  41. void deleteNode(int position) {
  42. if (head == null)
  43. return;
  44. Node node = head;
  45. if (position == 0) {
  46. head = node.next;
  47. return;
  48. }
  49. // Find the key to be deleted
  50. for (int i = 0; node != null && i < position - 1; i++)
  51. node = node.next;
  52. // If the key is not present
  53. if (node == null || node.next == null)
  54. return;
  55. // Remove the node
  56. Node next = node.next.next;
  57. node.next = next;
  58. }
  59. public void printList() {
  60. Node node = head;
  61. while (node != null) {
  62. System.out.print(node.item + " ");
  63. node = node.next;
  64. }
  65. }
  66. public static void main(String[] args) {
  67. LinkedList llist = new LinkedList();
  68. llist.insertAtEnd(1);
  69. llist.insertAtBeginning(2);
  70. llist.insertAtBeginning(3);
  71. llist.insertAtEnd(4);
  72. llist.insertAfter(llist.head.next, 5);
  73. System.out.println("Linked list: ");
  74. llist.printList();
  75. System.out.println("\nAfter deleting an element: ");
  76. llist.deleteNode(3);
  77. llist.printList();
  78. }
  79. }
// Linked list operations in C

#include <stdio.h>
#include <stdlib.h>

// Create a node
struct Node {
  int item;
  struct Node* next;
};

void insertAtBeginning(struct Node** ref, int data) {
  // Allocate memory to a node
  struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

  // insert the item
  new_node->item = data;
  new_node->next = (*ref);

  // Move head to new node
  (*ref) = new_node;
}

// Insert a node after a node
void insertAfter(struct Node* node, int data) {
  if (node == NULL) {
    printf("the given previous node cannot be NULL");
    return;
  }

  struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
  new_node->item = data;
  new_node->next = node->next;
  node->next = new_node;
}

void insertAtEnd(struct Node** ref, int data) {
  struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
  struct Node* last = *ref;

  new_node->item = data;
  new_node->next = NULL;

  if (*ref == NULL) {
    *ref = new_node;
    return;
  }

  while (last->next != NULL)
    last = last->next;

  last->next = new_node;
  return;
}

void deleteNode(struct Node** ref, int key) {
  struct Node *temp = *ref, *prev;

  if (temp != NULL && temp->item == key) {
    *ref = temp->next;
    free(temp);
    return;
  }
  // Find the key to be deleted
  while (temp != NULL && temp->item != key) {
    prev = temp;
    temp = temp->next;
  }

  // If the key is not present
  if (temp == NULL) return;

  // Remove the node
  prev->next = temp->next;

  free(temp);
}

// Print the linked list
void printList(struct Node* node) {
  while (node != NULL) {
    printf(" %d ", node->item);
    node = node->next;
  }
}

// Driver program
int main() {
  struct Node* head = NULL;

  insertAtEnd(&head, 1);
  insertAtBeginning(&head, 2);
  insertAtBeginning(&head, 3);
  insertAtEnd(&head, 4);
  insertAfter(head->next, 5);

  printf("Linked list: ");
  printList(head);

  printf("\nAfter deleting an element: ");
  deleteNode(&head, 3);
  printList(head);
}
// Linked list operations in C++

#include <stdlib.h>
#include <iostream>

using namespace std;

// Create a node
struct Node {
  int item;
  struct Node* next;
};

void insertAtBeginning(struct Node** ref, int data) {

  // Allocate memory to a node
  struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));

  // insert the item
  new_node->item = data;
  new_node->next = (*ref);

  // Move head to new node
  (*ref) = new_node;
}

// Insert a node after a node
void insertAfter(struct Node* prev_node, int data) {
  if (prev_node == NULL) {
    cout << "the given previous node cannot be NULL";
    return;
  }

  struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
  new_node->item = data;
  new_node->next = prev_node->next;
  prev_node->next = new_node;
}

void insertAtEnd(struct Node** ref, int data) {
  struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
  struct Node* last = *ref;

  new_node->item = data;
  new_node->next = NULL;

  if (*ref == NULL) {
    *ref = new_node;
    return;
  }

  while (last->next != NULL)
    last = last->next;

  last->next = new_node;
  return;
}

void deleteNode(struct Node** ref, int key) {
  struct Node *temp = *ref, *prev;

  if (temp != NULL && temp->item == key) {
    *ref = temp->next;
    free(temp);
    return;
  }
  // Find the key to be deleted
  while (temp != NULL && temp->item != key) {
    prev = temp;
    temp = temp->next;
  }

  // If the key is not present
  if (temp == NULL) return;

  // Remove the node
  prev->next = temp->next;

  free(temp);
}

// Print the linked list
void printList(struct Node* node) {
  while (node != NULL) {
    cout << node->item << " ";
    node = node->next;
  }
}

// Driver program
int main() {
  struct Node* head = NULL;

  insertAtEnd(&head, 1);
  insertAtBeginning(&head, 2);
  insertAtBeginning(&head, 3);
  insertAtEnd(&head, 4);
  insertAfter(head->next, 5);

  cout << "Linked list: ";
  printList(head);

  cout << "\nAfter deleting an element: ";
  deleteNode(&head, 3);
  printList(head);
}