反转链表
class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* temp; ListNode* cur = head; ListNode* pre = NULL; while(cur){ temp = cur->next; cur->next = pre; pre = cur; cur = temp; } return pre; } };
经过几天的坚持刷题下来,双指针法感觉很简单。但是递归法还没太明白,准备周末再消化消化。
附上双指针法记录
两两交换链表中的节点
class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode* varHead = new ListNode(0); varHead->next = head; ListNode* cur = varHead; while(cur->next != nullptr && cur->next->next != nullptr){ ListNode* temp = cur->next; ListNode* temp1 = cur->next->next->next; cur->next = cur->next->next; cur->next->next = temp; cur->next->next->next = temp1; cur = cur->next->next; } return varHead->next; } };
跟着随想录用的虚拟头结点法。实际上写交换的时候想了一会儿 感觉有点麻烦,理了半天。看到了递归的方法。空下来仔细研究一下.
class Solution { public: ListNode* swapPairs(ListNode* head) { if(head == NULL || head->next == NULL){ return head; } ListNode* node = head->next; ListNode* next = node->next; node->next = head; head->next = swapPairs(next); return node; } };
递过的方法。对于递归一直不太明白。
删除链表的倒数第N个节点
19. 删除链表的倒数第 N 个结点 - 力扣(LeetCode)
class Solution { public: ListNode* removeNthFromEnd(ListNode* head, int n) { ListNode* varHead = new ListNode(0); varHead->next = head; ListNode* fastNode = varHead; ListNode* slowNode = varHead; while(n-- && fastNode != NULL ){ fastNode = fastNode->next; } fastNode = fastNode->next; while(fastNode != NULL){ fastNode = fastNode->next; slowNode = slowNode->next; } slowNode->next = slowNode->next->next; return varHead->next; } };
很典型的双指针法。细节上没注意。第一个循环完毕之后快指针要再移动一格,这样慢指针就不会刚好指向要删除的元素而是他的上一个。
标签:head,ListNode,cur,fastNode,Day5,varHead,next,LeetCode,刷题 From: https://www.cnblogs.com/tianmaster/p/16856347.html