剑指offer 面试题57 删除链表中重复的结点
题目:
在一个排序的链表中,如何删除重复的结点?
例如,链表 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5,
删除重复结点后为 1 -> 2 - > 3 -> 4 -> 5
package algorithm.foroffer.top60;
import org.junit.Test;
/**
* description:
*
* @author liyazhou
* @create 2017-06-18 15:12
* 面试题57:删除链表中重复的结点
*
* 题目:
* 在一个排序的链表中,如何删除重复的结点?
* 例如,链表 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5,
* 删除重复结点后为 1 -> 2 - > 3 -> 4 -> 5
*
* 考查点:
* 1. 链表
*
* 思路:
* 1. 如果当前结点跟后继结点相等,则将当前结点指向其后继结点的后继结点
*/
class Node57 {
int value;
Node57 next;
public Node57 (int _value){ value = _value; }
@Override
public String toString(){
return String.format("value = %s, next = %s", value, next == null ? null : next.value );
}
}
public class Test57 {
public Node57 deleteDuplication(Node57 head){
for (Node57 currNode = head; currNode.next != null; currNode = currNode.next){
if (currNode.value == currNode.next.value)
currNode.next = currNode.next.next;
}
return head;
}
@Test
public void test(){
Node57 node0 = new Node57(0);
Node57 node1 = new Node57(1);
Node57 node2 = new Node57(2);
Node57 node3 = new Node57(3);
Node57 node4 = new Node57(3);
Node57 node5 = new Node57(4);
Node57 node6 = new Node57(4);
Node57 node7 = new Node57(5);
node0.next = node1;
node1.next = node2;
node2.next = node3;
node3.next = node4;
node4.next = node5;
node5.next = node6;
node6.next = node7;
Node57 newHead = deleteDuplication(node0);
for (; newHead != null; newHead = newHead.next)
System.out.println(newHead.value);
}
}
面试题57:删除链表中重复的结点
题目:
在一个排序的链表中,如何删除重复的结点?
例如,链表 1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5,
删除重复结点后为 1 -> 2 -> 5
2017-8-19 20:49:45
private class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
// 双指针
public ListNode deleteDuplication(ListNode pHead)
{
ListNode dummyHead = new ListNode(-1); // small trick,哑结点(头指针)
dummyHead.next = pHead;
ListNode first = dummyHead;
ListNode second = pHead;
int currVal;
while(second != null){
currVal = second.val;
// 情况一:当前结点跟后面的结点相等,则删除这些结点
if (second.next != null && second.next.val == currVal){
while (second != null && second.val == currVal){
second = second.next;
}
first.next = second; // 此时只需要删除重复的元素,first不需要移动
} else{ // 情况二:当前结点跟后面的结点不相等,则向后移动这两个指针
// first.next = second;
first = second;
second = second.next;
}
}
return dummyHead.next;
}