链表
1.链表理论基础
2.移除链表元素
3.设计链表
都使用虚拟头结点
3.1获取第n个节点:
首先进行条件判断n<0||n>size-1;
通过函数
cur = dummyhead->next;(头结点)
while(n--){
cur = cur->next};
return cur->next;
3.2头部插入节点
(要先让newnode指向head(dummy->next),然后再让dummy->next指向newnode,但是因为这个是头节点,所以可以先让让dummy->next先指向newnode,但是如果不是头结点的话,先让dummy->next指向newnode的话就会导致丢失原来的dummy->next的信息。)
newnode = new node()
newnode->next = dummyhead->next;
dummyhead->next = newnode;
3.3尾部插入节点
先定义一个新的节点,要在尾部插入节点,一定要cur指针指向尾节点,才能插入尾部的节点,让cur节点直接指向我们的newnode。
newnode = new node();
cur = dummyhead
# 一直让cur指向尾节点
while(cur->next != NULL){
cur = cur->next;
}
cur->next = newnode;
3.4第n个节点前插入节点
遍历寻找第n个节点while(n),多思考极端情况,如果是第0个节点前插入,那这个就不执行了。只有保证第n个节点是cur->next,才能用cur来操作,在cur->next之前添加一个节点。
newnode = new node();
cur = dummyhead
# 一直让cur指向尾节点
while(n){
cur = cur->next;
n--;
}
newnode->next = cur->next;
cur->next = newnode;
size++;
3.5 删除第n个节点。
找到第n个节点,第n个节点一定是cur->next,然后让cur->next指向cur->next->next.
#用n=0来判断特殊条件。
while(n){
cur=cur->next;
n--
}
cur->next = cur->next->next;
size--;