单链表的题目,咕咕咕
1.咕
203. 移除链表元素 - 力扣(LeetCode)
给你一个链表的头节点 head
和一个整数 val
,请你删除链表中所有满足 Node.val == val
的节点,并返回 新的头节点
struct ListNode* removeElements(struct ListNode* head, int val) {struct ListNode* newnode=NULL;struct ListNode* newhead=NULL;while(head){if(head->val!=val)//进行一个尾插就行了{if(newnode==NULL){newnode=head;newhead=head;}else{newnode->next=head;newnode=newnode->next;}}head=head->next;}if(newnode)newnode->next=NULL;return newhead;
}
2.咕咕
206. 反转链表 - 力扣(LeetCode)
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
struct ListNode* reverseList(struct ListNode* head) {struct ListNode* l1=NULL;struct ListNode* l2=head;while(l2!=NULL){struct ListNode* l3=l2->next;l2->next=l1;l1=l2;l2=l3;}return l1;
}
//定义3个指针NULL 1 -> 2 -> 3 -> NULLl1<- l2<- l3l1<- l2 <- l3
3.咕咕咕
876. 链表的中间结点 - 力扣(LeetCode)
给你单链表的头结点 head
,请你找出并返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
struct ListNode* middleNode(struct ListNode* head) {if(head==NULL) return NULL;struct ListNode* l1=head;struct ListNode* l2=head;while(l2&&l2->next){l1=l1->next;l2=l2->next->next;}return l1;
}
//快慢指针,找链表中点
4.咕咕咕咕
21. 合并两个有序链表 - 力扣(LeetCode)
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {if(list1==NULL) return list2;if(list2==NULL) return list1;struct ListNode* l1=list1;struct ListNode* l2=list2;
//申请一个“哨兵位”,放在最前面,可以简化一会尾插的代码,不用考虑尾插时链表为空的情况struct ListNode* newhead=(struct ListNode*)malloc(sizeof(struct ListNode));struct ListNode* pcur=newhead;while(l1&&l2){if(l1->val>l2->val){pcur->next=l2;l2=l2->next;}else{pcur->next=l1;l1=l1->next;}pcur=pcur->next;}if(l1) pcur->next=l1;if(l2) pcur->next=l2;newhead=newhead->next;return newhead;
}
5.咕咕咕咕咕
链表的回文结构_牛客题霸_牛客网
对于一个链表,请设计一个时间复杂度为O(n),额外空间复杂度为O(1)的算法,判断其是否为回文结构。
给定一个链表的头指针A,请返回一个bool值,代表其是否为回文结构。保证链表长度小于等于900。
class PalindromeList {
public:bool chkPalindrome(ListNode* head) {if(head == nullptr || head->next == nullptr) return true;
//先快慢指针找中点ListNode* slow = head;ListNode* fast = head;while(fast && fast->next) {slow = slow->next;fast = fast->next->next;}
//中点之后的链表反转ListNode* reversed = nullptr;ListNode* current = slow;while(current) {ListNode* nextNode = current->next;current->next = reversed;reversed = current;current = nextNode;}
//进行比对ListNode* p1 = head;ListNode* p2 = reversed;bool isPalindrome = true;while(p1 && p2) {if(p1->val != p2->val) {isPalindrome = false;break;}p1 = p1->next;p2 = p2->next;}return isPalindrome;}
};