給定一個排序鏈表,刪除全部重複的元素,使得每一個元素只出現一次。測試
試題連接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-list/code
public static ListNode deleteDuplicates(ListNode head) { if(head == null) return null; ListNode newNode = new ListNode(-1); newNode.val = head.val; newNode.next = null; ListNode p = newNode; while(head != null) { // System.out.println(newNode); if(head.val != p.val) { p.next = head; p = p.next; }else { head = head.next; p.next = null; } } return newNode; }
輸出結果:blog
public static ListNode deleteDuplicates(ListNode head) { if(head == null) return null; ListNode p1 = head; ListNode p2 = head.next; while (p2 != null) { if(p2.val == p1.val) { p1.next = p2.next; p2 = p2.next; }else { p2 = p2.next; p1 = p1.next; } } return head; }
測試結果:排序
struct ListNode* deleteDuplicates(struct ListNode* head){ if(head == NULL) return NULL; struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val = head->val; newNode->next = NULL; struct ListNode* p = newNode; while(head != NULL) { if(head->val != p->val) { p->next = head; p = p->next; }else { head = head->next; p->next = NULL; } } return newNode; }
測試結果:leetcode
struct ListNode* deleteDuplicates(struct ListNode* head){ if(head == NULL) return NULL; struct ListNode* p1 = head; struct ListNode* p2 = head->next; while (p2 != NULL) { if(p2->val == p1->val) { p1->next = p2->next; p2 = p2->next; }else { p2 = p2->next; p1 = p1->next; } } return head; }
測試結果:rem