首页 > 学院 > 开发设计 > 正文

LeetCode--Remove Duplicates from Sorted List

2019-11-14 21:27:54
字体:
来源:转载
供稿:网友
LeetCode--Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear onlyonce.

For example,Given1->1->2, return1->2.Given1->1->2->3->3, return1->2->3.

LeetCode上很简单的一道题,处理链表将链表中重复的数值去除只保留一个。大致流程如下:

1.先判断链表是否为空或只有一个结点,是的话直接返回,否则进行一般处理。

2.head为前一个结点,nextNode为后head指向的后一个节点,nextNode不为空时说明没有到达链表尾部,进入while循环。

3.注意head.val==nextNode.val时,考虑超过两个重复值的情况,将head的下一节点指向nextNode的下一个节点,去除nextNode,head结点不变。

 head.val!=nextNode.val时,head后移指向nextNode。

最后将nextNode赋值为next指向的下一节点,继续循环比较。


/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { *         val = x; *         next = null; *     } * } */public class Solution {    public ListNode deleteDuplicates(ListNode head) {        ListNode result = head;        if(head==null||head.next==null)            return head;        else{            ListNode nextNode = head.next;            while(nextNode!=null){            if(head.val == nextNode.val)                head.next = nextNode.next;            else                head = nextNode;            nextNode = head.next;            }        }        return result;    }}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表