单向链表 代码
#include <stdio.h>
#include <stdlib.h>
struct Node {
int val;
struct Node* next;
};
struct Node* createList() {
struct Node* head = (struct Node* )malloc(sizeof(struct Node));
head->val = 0;
head->next = NULL;
return head;
}
int addNode(struct Node* head, int val){
if(!head){
return -1;
}
struct Node* cur = head;
for(int i=0;cur->next; i++){
cur = cur->next;
}
struct Node* newNode = (struct Node* )malloc(sizeof(struct Node));
newNode->val = val;
cur->next = newNode;
newNode->next = NULL;
return 0;
}
int insertNode(struct Node* head, int val, int pos) {
if (!head || pos < 1) {
return -1;
}
struct Node* cur = head;
for (int i = 1; i < pos && cur; ++i) {
cur = cur->next;
}
if (!cur) {
return -1;
}
struct Node* newNode = (struct Node* )malloc(sizeof(struct Node));
newNode->val = val;
newNode->next = cur->next;
cur->next = newNode;
return 0;
}
int deleteNode(struct Node* head, int pos) {
if (!head || pos < 1) {
return -1;
}
struct Node* cur = head;
for (int i = 1; i < pos && cur; ++i) {
cur = cur->next;
}
if (!cur || !cur->next) {
return -1;
}
struct Node* delNode = cur->next;
cur->next = delNode->next;
free(delNode);
return 0;
}
void printList(struct Node* head) {
if (!head) {
return;
}
struct Node* cur = head->next;
while (cur) {
printf("%d ", cur->val);
cur = cur->next;
}
printf("\n");
}
void destroyList(struct Node* head) {
if (!head) {
return;
}
struct Node* cur = head->next;
while (cur) {
struct Node* nextNode = cur->next;
free(cur);
cur = nextNode;
}
free(head);
}
int main() {
struct Node* head = createList();
insertNode(head, 1, 1);
insertNode(head, 2, 2);
insertNode(head, 3, 3);
insertNode(head, 6, 6);
addNode(head,666);
printList(head);
deleteNode(head, 2);
printList(head);
destroyList(head);
return 0;
}