题目:删除排序链表中的重复数字 II

来源:互联网 发布:吉永小百合 长相 知乎 编辑:程序博客网 时间:2024/06/05 10:41

给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。


您在真实的面试中是否遇到过这个题?

Yes





样例

给出1->2->3->3->4->4->5->null,返回1->2->5->null

给出1->1->1->2->3->null,返回 2->3->null
标签 Expand   


解题思路:
当前节点cur.val若是cur.next.val的节点相同,则把遍历把与cur.val相等的节点都找到,并且跳过。若是当前节点cur.val若是cur.next.val的节点不相同,则将该节点放入res中。
/*** Definition for ListNode* public class ListNode {*     int val;*     ListNode next;*     ListNode(int x) {*         val = x;*         next = null;*     }* }*/public class Solution {    /**     * @param ListNode head is the head of the linked list     * @return: ListNode head of the linked list     */    public static ListNode deleteDuplicates(ListNode head) {        // write your code          if (null == head)               return null;          ListNode res = new ListNode(0);          ListNode pre = res;          ListNode cur = head;          while (cur != null) {               if (cur.next!=null&&cur.val == cur.next.val) {                    while (cur.next!=null&&cur.val == cur.next.val) {                         cur = cur.next;                    }               }else{                    pre.next = cur;                    pre = pre.next;               }               cur = cur.next;                        }          //处理最后一个节点          pre.next = cur;          return res.next;    }}

0 0
原创粉丝点击