每日算法题【链表】:移除链表元素、反转链表
(6)删除链表中等于给定值的所有结点
-
203. 移除链表元素 - 力扣(LeetCode)
-
解题思路:
创建一个新链表,将不等于这个值的节点都尾插到新链表当中,最后返回新链表
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ typedef struct ListNode ListNode; //创建新链表,将值不等于val的尾插到新链表 struct ListNode* removeElements(struct ListNode* head, int val) {//创建一个新链表ListNode * newHead,*newTail;newHead = newTail = NULL;//循环遍历原链表找不同节点ListNode* cur = head;while(cur){//找值不为val的尾插到新链表当中if(cur->val != val){//链表为空if(newHead == NULL){newHead = newTail = cur;}else{//链表不为空newTail->next = cur;//尾插newTail = newTail->next;//newtail向后移动一个节点}}cur = cur->next;}//确保新链表的最后一个节点的next指针为NULL,避免可能的多余链接。if(newTail){newTail->next = NULL;}return newHead; }
(7)反转一个单链表
-
[206. 反转链表 - 力扣(LeetCode)]:
-
解题方法一:
取原链表中的节点,然后头插到newhead新链表中
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*///取原链表中的节点,然后头插到newhead新链表中 struct ListNode* reverseList(struct ListNode* head) {struct ListNode * cur = head;struct ListNode * newhead = NULL;//循环遍历取出链表节点while(cur){//先拿到cur->nextstruct ListNode* next = cur->next;//进行头插cur->next = newhead;//newhead指向新的头结点newhead = cur;//接着遍历原链表的下一个节点cur = next;}return newhead; }
-
解题思路二:
- 每次迭代中,将当前节点
n2
的next
指针指向前驱节点n1
,实现反转 - 然后三个指针向前移动:
n1
移动到当前n2
的位置n2
移动到n3
的位置- 如果
n3
不为空,n3
移动到它的下一个节点
- 当
n2
为空时(即已经处理完所有节点),循环结束 - 最后返回
n1
,它现在指向反转后的新头节点
struct ListNode* reverseList(struct ListNode* head) {//如果传入的链表头指针head为空,直接返回NULL,因为空链表不需要反转if(head == NULL){return NULL;}struct ListNode* n1,*n2,*n3;n1 = NULL;n2 = head;n3 = head->next;while(n2){//翻转n2->next = n1;//迭代往后走n1 = n2;n2 = n3;if(n3){n3 = n3->next;}}return n1; }
- 每次迭代中,将当前节点