C++实现单向链表

#include <iostream>
using namespace std;
int counter;
struct Node{
Node* next;
int data;
bool hasNext;

};
void addNode(Node* head,Node* node){
node->next=head->next;
head->next=node;
counter+=1;
}
void showListData(Node* head){
head=head->next;//ignore the head node
while(true){
cout<<head->data<<"\t";
head=head->next;
if(head->next==NULL){
cout<<head->data<<endl;
break;
}
}
cout<<endl;
}
void showListForLoop(Node* head){
for(int i=0;i<=counter;i++){
cout<<head->data<<"\t";
head=head->next;
}
}
void deleteNode(Node* head,int index){
if(index==1){
head->next;
}
Node* p = head;
for(int i = 1;i<index;i++){
p=p->next;
}
Node* node = p->next;
p->next = p->next->next;
delete(node);
}
void main(){
Node* head = new Node;
head->next=NULL;
head->data=100;
for(int i=1;i<=10;i++){
Node* node = new Node;
node->data=i;
addNode(head,node);

}
cout<<"counter:"<<counter<<endl;
showListData(head);
deleteNode(head,5);
showListData(head);
// showListForLoop(head);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 C 语言中,我们可以通过定义一个结构体来实现完整的单向链表。 首先,我们定义一个表示链表节点的结构体,包含一个数据项和一个指向下一个节点的指针: ```c struct Node { int data; struct Node* next; }; ``` 然后,我们可以编写一些函数来操作链表。下面是一些常用的操作函数: 1. 创建链表:创建一个空链表,并返回指向链表头节点的指针。 ```c struct Node* createList() { return NULL; } ``` 2. 插入节点:在链表的特定位置插入一个新节点。 ```c void insertNode(struct Node** head, int data, int position) { struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; if (position == 0) { newNode->next = *head; *head = newNode; } else { struct Node* current = *head; int i; for (i = 0; i < position - 1 && current != NULL; i++) { current = current->next; } if (current != NULL) { newNode->next = current->next; current->next = newNode; } } } ``` 3. 删除节点:删除链表中特定位置的节点。 ```c void deleteNode(struct Node** head, int position) { if (*head == NULL) { return; } struct Node* temp = *head; if (position == 0) { *head = temp->next; free(temp); return; } int i; for (i = 0; temp != NULL && i < position - 1; i++) { temp = temp->next; } if (temp == NULL || temp->next == NULL) { return; } struct Node* nextNode = temp->next->next; free(temp->next); temp->next = nextNode; } ``` 4. 打印链表:遍历链表并打印每个节点的数据。 ```c void printList(struct Node* head) { struct Node* current = head; while (current != NULL) { printf("%d ", current->data); current = current->next; } printf("\n"); } ``` 这些函数可以帮助我们创建、插入、删除和打印链表。以下是示例使用代码: ```c int main() { struct Node* myList = createList(); insertNode(&myList, 1, 0); insertNode(&myList, 2, 1); insertNode(&myList, 3, 2); printList(myList); // 输出:1 2 3 deleteNode(&myList, 1); printList(myList); // 输出:1 3 return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值