链表问题难道在于临界点的处理,主要考察coding能力
注意:一般while循环里的条件,cur->next->next如果想要程序正常运行,就必须满足cur和cur->next都不是空指针,但是cur->next->next可以是空指针,因为没有对他进行使用。
//双指针法 class Solution { public: ListNode* reverseList(ListNode* head) { ListNode*cur = head, *pre = nullptr, *tmp = nullptr; while (cur) { tmp = cur->next; cur->next = pre; pre = cur; cur = tmp; } return pre; } };
思路:cur结点后面两个数进行交换,如果后面不够就直接返回
class Solution { public: ListNode* swapPairs(ListNode* head) { ListNode *dummyHead = new ListNode(0, head); ListNode *cur = dummyHead; while (cur->next && cur->next->next) { ListNode *node1 = cur->next; ListNode *node2 = cur->next->next; ListNode *node3 = cur->next->next->next;//记录下一个节点后需要换位的结 cur->next = node2; node1->next = node3; node2->next = node1; cur = node1; } return dummyHead->next; } };
class Solution { public: ListNode* reverse(ListNode *head) { ListNode *cur = head; ListNode *pre = nullptr; ListNode *next = nullptr; while (cur) {//当cur为nullptr时,就不需要和前者有联系了,因为前者就是头结点啊。 next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } ListNode* reverseBetween(ListNode* head, int left, int right) { ListNode *pre = nullptr; ListNode *rightnode = nullptr; ListNode *leftnode = nullptr; ListNode *dummyHead = new ListNode(0, head); ListNode *tmp = dummyHead;//暂时保存头结点 ListNode *end = nullptr; for (int i = 0; i<left-1; i++) {//找到left左边的一个节点 tmp = tmp->next; } pre = tmp; leftnode = pre->next; for (int i = 0; i<right - left +1; i++) { tmp = tmp->next; } rightnode = tmp; end = rightnode->next; //切断连接 rightnode->next = nullptr; rightnode = reverse(leftnode); pre->next = rightnode; leftnode->next = end; return dummyHead->next; } };