关键词:链表,增删改查操作。
head pointer 插入删除会影响头指针
|
??? [ ] -> [ ] -> [ ]
head node 常用方法,即头指针为空
[x] -> [ ] -> [ ]
C实现
初始化
struct Node {
int data;
struct Node* next;
};
//typedef struct Node* LList; 取别名
void init(struct Node** phead ) {
*phead = NULL;
}
创建节点
struct Node* createNode(int x) {
struct Node* t;
t = (struct Node*)malloc(sizeof(struct Node));
t->next = NULL;
t->data = x;
return t;
}
查找第K个节点
struct Node* findKth(struct Node* head, int k) {
int count =1;
struct Node* p;
p = head;
while(p && count <k) {
p = p->next;
count++;
}
return p;
}
在K处插入节点
int insert(struct Node** phead, int k, int x ) {
if (k<0) {
return 0;
} else if(k==1) {
struct Node* t;
t = createNode(x);
t->next = *phead;
*phead = t;
return 1;
} else {
struct Node* p;
// 先找第k-1 个位置
p = findKth(*phead, k-1);
/*
printf("\n第k-1位置的值是%d\n",p->data);
出错!因为p->data 在 p 为空时为空!
*/
if(p) {
struct Node* t;
t = createNode(x);
t->next = p->next;
p->next = t;
return 1;
} else {
return 0;
}
}
}
删除第K个节点
int removeNode(struct Node** phead, int k, int *px) {
if (k<0) {
return 0;
} else if(k==1) {
if(*phead) {
*px = (*phead)->data;
*phead = (*phead)->next;
return 1;
} else {
return 0;
}
} else {
struct Node* p;
p = findKth(*phead, k);
if (p==NULL || p->next==NULL) {
return 0;
}
struct Node* t;
t = p->next;
p->next = t->next;
*px = t->data;
free(t);
return 1;
}
}
获取链表长度,打印链表
int getLength(struct Node* head) {
int len = 0;
while(head) {
len++;
head = head->next;
}
return len;
}
void printList(struct Node* head) {
printf("链表:");
while(head) {
printf("%d,", head->data);
head = head->next;
}
printf("\n");
}
Java有很多封装的包,实现更简单。
package n3_LinearStructure;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Stack;
public class LinkList {
public static void main(String[] args) {
LinkedList<Integer> a = new LinkedList<>();
a.add(11);
a.add(22);
// a.remove(11);
System.out.println(a);
// [11, 22]
}
}
C++实现较为尴尬。
#include <iostream>
#include <list>
#include <vector>
#include <stack>
using namespace std;
int main(){
list<int> a;
a.push_back(11);
a.push_back(22);
a.push_back(33);
// list<int>::iterator it;
// for (it=a.begin(); it!=a.end(); it++){
// cout << &(*it) << "," << *it << endl;
// }
for(auto it:a )cout<< it<<endl;
cout << endl;
return 0;
}