题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
原始思路:保存前一位的指针,这样在重复的时候,可以直接用next指向新的位置,需要注意的是开始时候,需要进行额外的判断是否有重复,才能形成错位的指针。
原始代码:
public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode req = head; ListNode pre = head; //判断初始是否有重复 while(head != null){ head = head.next; // 直到没有重复,head位于pre的下一位 if(head != null && pre.val == head.val){ do{ head = head.next; } while(head!=null && head.val == pre.val); pre = head; req = head; }else break; } //过程中判断,pre始终在head前一位 while(head != null){ head = head.next; if(head!=null && pre.next.val == head.val){ do{ head = head.next; } while(head!=null && head.val == pre.next.val); pre.next = head; } else pre = pre.next; } return req; } }
修改思路:可以建立一个虚拟表头,next指向head,这样可以把原始代码中初始部分的额外判断优化掉,代码十分简洁。
修改后代码:
public class Solution { public ListNode deleteDuplicates(ListNode head) { ListNode dunmy = new ListNode(Integer.MIN_VALUE); dunmy.next = head; ListNode pre = dunmy; while(head != null){ head = head.next; if(head!=null && pre.next.val == head.val){ do{ head = head.next; } while(head!=null && head.val == pre.next.val); pre.next = head; } else pre = pre.next; } return dunmy.next; } }
时间: 2024-11-13 06:57:21