203.移除链表元素
虚拟头节点
虚拟头节点为dummy head,利用这个虚拟头节点实现统一的删除链表中元素的方法。
关键点是new一个dummy head,然后令current = dummy head,这里之所以不是current = dummy head->next 是因为我们要查看的是整个链表中的每个元素,如果令current = dummy head->next 的话,如果dummy head->next 是我们要删除的那个元素的话,那么删除current,dummy head又要重新表示。我们要删除的应该是current->next,所以令current = dummy head->next。
最后return的也不是head而是dummy head。
struct ListNode* removeElements(struct ListNode* head, int val)
{
typedef struct ListNode ListNode;
ListNode *dummyhead;
dummyhead = (ListNode *)malloc(sizeof(ListNode));//定义虚拟头结点
dummyhead->next = head;
//ListNode *current = dummyhead;
ListNode *current;
current = dummyhead;
while(current->next != NULL){
if(current->next->val == val){
ListNode *tmp = current->next;
current->next = current->next->next;
free(tmp);
}
else{
current = current->next;
}
}
head = dummyhead->next;
free(dummyhead);
return head;
//return dummyhead; 这样不行会把不属于这个链表的虚拟头节点也给输出出来 不符合题的要求
}
707.设计链表
设计链表分为三个部分:
按下标查找返回链表的值
按位置插入链表
分为插入头结点和尾结点,可以统一划为插入节点。
先判断index值,如果小于0则设置为0,如果超过size则返回空。
引入虚拟头结点,方便做头插入,注意size++。
按位置删除链表
也是引入虚拟头结点。size--。
class MyLinkedList {
int size;
ListNode head;
public MyLinkedList() {
size = 0;
head = new ListNode(0);
}
public int get(int index) {
if(index < 0 || index >= size){
return -1;
}
ListNode currentnode = head;
for(int i = 0; i <= index; i++) {
currentnode = currentnode.next;
}
return currentnode.val;
}
public void addAtHead(int val) {
addAtIndex(0,val);
}
public void addAtTail(int val) {
addAtIndex(size,val);
}
public void addAtIndex(int index, int val) {
if (index > size){
return;
}
if (index < 0) {
index = 0;
}
size = size + 1;
ListNode pred = head;
for (int i = 0; i < index; i++) {
pred = pred.next;
}
ListNode toAdd = new ListNode(val);
toAdd.next = pred.next;
pred.next = toAdd;
}
public void deleteAtIndex(int index) {
if (index < 0 || index >= size) {
return;
}
size--;
ListNode pred = head;
for(int i = 0; i < index; i++) {
pred = pred.next;
}
pred.next = pred.next.next;
}
}
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList obj = new MyLinkedList();
* int param_1 = obj.get(index);
* obj.addAtHead(val);
* obj.addAtTail(val);
* obj.addAtIndex(index,val);
* obj.deleteAtIndex(index);
*/
206.反转链表
设置三个链表 pre = null cur = head temp = null
pre用来表示cur的前一个节点 cur表示现在正在遍历的节点 temp用来存储cur.next节点
以while(cur != null)为条件 一个一个遍历head链表
将pre cur理解为移动的指针
一个一个反转 在while循环里一步一步向后移动 直到cur为空 则循环结束
最后返回的是pre