LeetCode之24----Swap Nodes in Pairs

mac2022-06-30  65

题目:

Given a linked list, swap every two adjacent nodes and return its head.

For example, Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题目大意:

  给定一条链表,将链表相邻的两个节点交换,返回交换后的链表。

思路:

  本题比较简单,大致解题方向有两种:交换节点的值、交换节点的指向。   1、交换节点的值:最简单的方法就是交换两个节点的值,达到交换的目的。   2、交换相邻节点的指向,在即当p2 = p1->next时执行p1->next = p2->next,p2->next = p1。但是在交换的过程中还要保证交换后p2的前驱节点是交换前p1的前驱。   3、还是交换节点的思路,只不过这次的考虑方向不是进行循环交换,而是通过递归来交换。递归的这种程序简洁,重点在于思考方式的不同。在这道题里递归的思考方式是考虑一对的情况,然后将这个分析结果应用到后边的节点,递归下去,解出结果。

代码:

换值:

ListNode* swapPairs(ListNode* head) { ListNode *p1 = head, *p2; int tmp; while(p1) { p2 = p1->next; if (p2) { tmp = p1->val; p1->val = p2->val; p2->val = tmp; p1 = p1->next; } p1 = p1->next; } return head; }

换指针:

ListNode* swapPairs(ListNode* head) { ListNode *p1 = head, *p2, *tmp; if (p1 && p1->next) { head = head->next; } tmp = head; while(p1) { p2 = p1->next; if (p2) { p1->next = p2->next; p2->next = p1; if (tmp != head) tmp ->next = p2; tmp = p1; } p1 = p1->next; } return head; }

换指针(递归版):

ListNode* swapPairs(ListNode* head) { ListNode* p1; if(head && head->next){ p1 = head->next; head->next = swapPairs(head->next->next); p1->next = head; head = p1; } return head; }

转载于:https://www.cnblogs.com/jungzhang/p/5547302.html

最新回复(0)