One: remove the linked list element
.Basic idea: 1 ) Determine whether the linked list is empty, if it is empty, return NULL
2 ) Traverse the linked list, find the node before the corresponding val , and link it with the next node of val .
3 ) Pit point: there will be a situation where the head node is val , so we need to deal with the problem of the head node additionally.
It is more convenient to use two pointers for this question.
draw
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
while(head&&head->val==val)//找新的头节点,改新头节点的head->val!=val
{
head = head->next;//更新head
}
if(head==NULL)//判断新头节点是否出现示例2或示例3的极端情况
{
return NULL;
}
struct ListNode* prev = head;//创建指针,记录当前head的地址
while(prev->next)
{
if(prev->next->val == val)//判断节点val的值是否与val相等。
{
prev->next = prev->next->next;//相等就进行2)中的链接
}
else
{
prev = prev->next;//更新prev
}
}
return head;
}
two:
Basic idea: 1) Determine whether the linked list is empty, if it is empty, return NULL
2) Processing method:
i build a new head node and tail-interpolate the original data
ii Change the pointing of the original arrow
Drawing:
i。
Note: The loop end condition is cur==NULL
Every time you need to update cur and newHead, and finally return newHead
Since the loop ends when cur is empty, the next will become a null pointer, which requires special treatment
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head == NULL)//判断链表是否为空
{
return NULL;
}
struct ListNode* newHead = NULL,*cur = head,*next = head->next;
while(cur)
{
cur->next = newHead;//头插节点
newHead = cur;//更新节点newHead
cur = next;//更新cucr指针
if(next!=NULL)//防止next成为野指针
next = next->next;//更新next指针
}
return newHead;
}
ii. Forcibly reverse the arrow
Note: 1) For the convenience of processing, three pointer variables are set: prev, cur, next, which respectively record the nodes before, after, and after cur.
2) Similar to the idea of the above figure, it is still linking and updating nodes
Drawing:
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL)//判断链表是否为空
return NULL;
struct ListNode* prev = NULL;//
struct ListNode* cur = head;//
struct ListNode* next = head->next;//创建指针变量
while(cur)//循环
{
cur->next = prev;//链接节点
prev = cur;//更新prev
cur = next;//更新cur
if(next)//防止next成为野指针
next = next->next;//更新next
}
return prev;
}