题目
给定一个已排序的链表的头 head , 删除所有重复的元素,使每个元素只出现一次 。返回 已排序的链表 。
示例 1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3]
输出:[1,2,3]
分析
用一个指针从头结点开始遍历,如果当前元素和下个元素一致则更新当前指针的next结点为下个结点的下个结点,反之指针后移
public class LinkNode { int val; LinkNode next; public LinkNode(int data) { this.val = data; this.next = null; } } public class LinkList { LinkNode head; public LinkList() { this.head = null; } public LinkNode getHead() { return this.head; } //添加元素 public void addNode(int data) { LinkNode node = new LinkNode(data); if (this.head == null) { this.head = node; } else { LinkNode cur = this.head; while(cur.next != null) { cur = cur.next; } cur.next = node; } } //正序打印 public void print(LinkNode node) { while(node != null) { System.out.print(node.val); System.out.print(" "); node = node.next; } System.out.println(); } public void deleteRepeate() { LinkNode pNode = this.head; while(pNode != null && pNode.next != null) { if(pNode.val == pNode.next.val) { pNode.next = pNode.next.next; } else { pNode = pNode.next; } } print(this.head); } } public class removeDuplicatesfromSortedList { public static void main(String[] args) { LinkList list = new LinkList(); list.addNode(1); list.addNode(1); list.addNode(2); list.addNode(3); list.addNode(3); list.deleteRepeate(); } }
还没有评论,来说两句吧...