码迷,mamicode.com
首页 > 其他好文 > 详细

057_删除聊表中的重复的节点

时间:2014-09-13 22:49:16      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:io   os   ar   for   sp   c   amp   ad   new   

#include <iostream> 
#include <vector>
using namespace std;


typedef struct ListNode {
	int data;
	struct ListNode * next;
	ListNode(int d) : data(d), next(NULL){}
};

ListNode *initList(int *array, unsigned int length) {
	
	if(!array) {
		return NULL;
	}

	ListNode * head = NULL;
	head = new ListNode(array[0]);
	ListNode * p = head;
	head->next = NULL;
	
	unsigned int i = 1;
	for(; i < length; i++) {
		p->next = new ListNode(array[i]);
		p = p->next;		
	}

	
	return head;
	
} 

void printList(ListNode *head) {
	
	ListNode * p = head;
	if (!head){
		return;
	}
	while (p && p->next) {
		cout<<p->data<<"->";
		p = p->next; 
	}
	if (p) {
		cout<<p->data<<endl;
	}
	
}

ListNode *removeDuplicateNode(ListNode *head) {
	if (head == NULL) {
		return NULL;
	}
	ListNode *pre = head;
	ListNode *post = pre->next;
	while(pre != NULL && post != NULL) {
		if (pre->data == post->data) {//delete post node 
			pre->next = post->next;
			delete post;
			post = pre->next;
		} else {
			pre = pre->next;
			post = post->next;
		}
	}
	return head;
}

int main(){ 


	int i = 0;

	int array1[9] = {1, 1, 1, 2, 2, 3, 4, 4, 5};

	ListNode *head1 = NULL;


	head1 = initList(array1, 9);
	cout<<"list1:	";
	printList(head1);
	
	head1 = removeDuplicateNode(head1);
	printList(head1);	
	

	return 1;	
}

057_删除聊表中的重复的节点

标签:io   os   ar   for   sp   c   amp   ad   new   

原文地址:http://blog.csdn.net/wyj7260/article/details/39256323

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!