反轉一個單鏈表。指針
試題連接:https://leetcode-cn.com/problems/reverse-linked-list/code
public static ListNode reverseList(ListNode head) { if(head == null) return null; //構造頭指針 ListNode index = new ListNode(-1); index.next = head; ListNode pCurrent = head; while (pCurrent.next != null) { //使輔助移動到最後 pCurrent = pCurrent.next; } while (index.next != pCurrent) { ListNode temp = index.next; index.next = temp.next; temp.next = pCurrent.next; pCurrent.next = temp; } return index.next; }
輸出結果:blog
struct ListNode* reverseList(struct ListNode* head){ if(head == NULL) return NULL; //構造頭指針 struct ListNode* index = (struct ListNode*)malloc(sizeof(struct ListNode)); index->val = -1; index->next = head; struct ListNode* pCurrent = head; while (pCurrent->next != NULL) { //使輔助移動到最後 pCurrent = pCurrent->next; } while (index->next != pCurrent) { struct ListNode* temp = index->next; index->next = temp->next; temp->next = pCurrent->next; pCurrent->next = temp; } return index->next; }
輸出結果:遞歸
public static ListNode reverseList(ListNode head) { if(head == null || head.next == null) return head; // 0、1->2->3->4->5->null // 一、2->3->4->5->null // 二、3->4->5->null // 三、4->5->null // 四、5->null // 5 ListNode newNode = reverseList(head.next); // System.out.println(head); head.next.next = head; head.next = null; return newNode; }
輸出結果:leetcode
struct ListNode* reverseList(struct ListNode* head){ if(head == NULL || head->next == NULL) return head; struct ListNode* newNode = reverseList(head->next); head->next->next = head; head->next = NULL; return newNode; }
輸出結果:get