給定一個鏈表,兩兩交換其中相鄰的節點,並返回交換後的鏈表。java
你不能只是單純的改變節點內部的值,而是須要實際的進行節點交換。node
試題連接:https://leetcode-cn.com/problems/swap-nodes-in-pairs/緩存
public static ListNode swapPairs(ListNode head) { if(head == null || head.next == null) return head; //僞造出頭來 ListNode headIndex = new ListNode(-1); headIndex.next = head; //頭指針 ListNode p = headIndex.next; ListNode p0 = headIndex; while (p != null && p.next != null) { //緩存下一個結點 ListNode saveNode = p.next; p.next = saveNode.next; saveNode.next = p; p0.next = saveNode; p = p.next; p0 = p0.next.next; } return headIndex.next; }
測試結果:測試
struct ListNode* swapPairs(struct ListNode* head){ if(head == NULL || head->next == NULL) return head; //僞造出頭來 struct ListNode* headIndex = (struct ListNode*)malloc(sizeof(struct ListNode)); headIndex->val = -1; headIndex->next = head; //頭指針 struct ListNode* p = headIndex->next; struct ListNode* p0 = headIndex; while (p != NULL && p->next != NULL) { //緩存下一個結點 struct ListNode* saveNode = p->next; p->next = saveNode->next; saveNode->next = p; p0->next = saveNode; p = p->next; p0 = p0->next->next; } return headIndex->next; }
測試結果:3d