2013-10-14 49 views
0

尝试链接列表问题1.从cpp中打开编码访问。 - 写入代码以从未排序的链接列表中删除重复项。 继续操作 如果不允许使用临时缓冲区,您将如何解决此问题?删除链接列表中的重复项

您如何看待此实现?

#include "stdafx.h" 
#include <stdlib.h> 
struct node 
{ 
    int data; 
    struct node *next; 
}; 
struct node *head = (node*)malloc(sizeof(node)); 
struct node *tail = (node*)malloc(sizeof(node)); 

struct node* createNode(int data) 
{ 
    struct node *newNode = (node*)malloc(sizeof(node)); 
    newNode->data = data; 
    newNode->next = NULL; 
    head = newNode; 
    return newNode; 
} 

bool insertAfter(node * list, int data) 
{ 
    //case 1 - insert after head 
    struct node *newNode = (node*)malloc(sizeof(node)); 
    if (!list) 
    { 

     newNode->data = data; 
     newNode->next = head; 
     head = newNode; 
     return true; 
    } 

    struct node * curpos = (node *)malloc(sizeof(node)); 
    curpos = head; 
    //case 2- middle, tail of list 
    while (curpos) 
    { 
     if (curpos == list) 
     { 
      newNode->data = data; 
      if (curpos->next == NULL) 
      { 
       newNode->next = NULL; 
       tail = newNode; 
      } 
      else 
      { 
       newNode->next = curpos->next; 
      } 
      curpos->next = newNode; 
      return true; 
     } 
     curpos = curpos->next; 
    } 
} 

void deleteNode(node *runner, node * curr){ 

    //DELETE AT TAIL 
    if (runner->next->next == NULL) 
    { 
     runner->next = NULL;   
    } 
    else//delete at middle 
    { 
     runner->next = runner->next->next; 
    } 
} 


void removedups(node * list) 
{ 
    struct node * curr = (node*)malloc(sizeof(node)); 
    struct node * runner = (node*)malloc(sizeof(node)); 
    curr = head; 
    runner = curr; 
    while (curr != NULL){ 
     runner = curr; 
     while (runner->next != NULL){ 
      if (curr->data == runner->next->data){ 
       deleteNode(runner, curr); 
      } 
      if (runner->next!=NULL) 
       runner = runner->next; 
     } 
     curr = curr->next; 
    } 
} 

int _tmain(int argc, _TCHAR* argv[]) 
{ 
    struct node * list = (node*) malloc(sizeof(node)); 
    list = createNode(1); 
    insertAfter(list,2); 
    insertAfter(list, 2); 
    insertAfter(list, 3); 
    removedups(list); 
    return 0; 
} 
+1

'1.'你有内存泄漏。 '2。如果相同的值不相互跟随,则此代码不会删除重复项。 '''不要期望那次采访会有很好的结果。 '''学习STL。 – user1764961

+0

感谢指点2.更新代码 – user2864458

+0

这可能是更适合http://codereview.stackexchange.com/ – crashmstr

回答

2

它看起来更像是C代码,而不是C++。

如果是采访,尝试使用递归,他们主要询问链接列表问题,看看您是否适应它。只是为了测试你是否擅长不同的算法。

你有很多的malloc(这是C风格的动态内存分配),但你在哪里释放内存? 内存泄漏也是他们想要的听到你想想! 所以不要犹豫,大声说出来:现在我必须检查我没有搞乱内存!