How to create a Linked List in Python
- A linked list is a data structure made of a chain of node objects. Each node contains a value and a pointer to the next node in the chain.
- The head pointer points to the first node, and the last element of the list points to null. When the list is empty, the head pointer points to null.
# 节点类
class Node(object):
def __init__(self, data, Next = None):
self.data = data
self.next = Next
# 链表类:用于存放节点
class LinkedList(object):
def __init__(self):
self.head = None
# 判断链表是否为空
def isEmpty(self):
return self.head == None
# 给链表添加节点
def add(self, data):
newNode=Node(data) # 构建一个新的节点,该节点的值为data
# 头结点存在,把cur指向头结点,cur逐步跳到链表尾部,然后添加节点
if (self.head):
cur=self.head
while (cur.next):
cur = cur.next
cur.next=newNode # 通过next,在尾部不断连接节点
else: # 这是一个空链表,则在头结点处添加该节点
self.head=newNode
# 判断链表的长度
def size(self):
count=0
cur=self.head
while(cur):
count+=1
cur=cur.next
print(count)
# 搜索某个元素是否存在
def search(self,item):
cur=self.head
while(cur):
if cur.data==item:
return True
else:
cur=cur.next
return False
# 打印该链表
def printLL(self):
cur=self.head
while(cur):
print(cur.data)
cur=cur.next
if __name__ == '__main__':
L=LinkedList()
L.add(1)
L.add(2)
L.add(3)
# L.size()
# print(L.search(2)==True)
L.printLL()
#include <iostream>
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class LinkedList {
private:
ListNode *head;
public:
LinkedList():head(nullptr){} // 构造函数构建一个空的链表
// 判断链表是否为空
bool isEmpty() const {
return head == nullptr;
}
// 添加节点
void add(int data) {
// 创建一个新节点
ListNode *newNode = new ListNode(data);
if (head) {
ListNode *cur = head;
while (cur->next) {
cur = cur->next;
}
cur->next = newNode;
} else
head = newNode;
}
// 判断链表的长度
int size() {
int count = 0;
ListNode *cur = head;
while (cur) {
count++;
cur = cur->next;
}
return count;
}
// 搜索某个元素是否存在
bool search(int data) {
ListNode *cur = head;
while (cur) {
if (cur->val == data) {
return true;
}
else
cur = cur->next;
}
return false;
}
// 打印该链表
void printLL() {
ListNode *cur = head;
while (cur) {
std::cout << cur->val << std::endl;
cur = cur->next;
}
}
};
int main(){
ListNode n(1);
LinkedList L;
L.add(1);
L.add(2);
L.add(3);
// std::cout<<L.size()<<std::endl;
// std::cout<<L.search(2)<<std::endl;
L.printLL();
}