关于链表指针个数的思考

问题是在升序单链表中删除重复元素的节点

以下有两个代码

代码一:

struct ListNode* deleteDuplicates(struct ListNode* head ) {

if(head == NULL)

return NULL;

struct ListNode* cur = head;

while(cur->next)

{

struct ListNode* next = cur->next;

if(cur->val == next->val)

{

cur->next = next->next;

free(next);

}

else

{

cur = cur->next;

}

}

return head;

}

代码二:

struct ListNode* deleteDuplicates(struct ListNode* head)

{

if (head == NULL || head->next == NULL)

return head;

struct ListNode* cur = head;

struct ListNode* next = cur->next;

struct ListNode* nextnext = next->next;

while (next)

{

if (cur->val != next->val)

{

cur = next;

next = next->next;

if (nextnext)

nextnext = nextnext->next;

}

else

{

cur->next = nextnext;

free(next);

next = nextnext;

if (nextnext)

nextnext = nextnext->next;

}

}

return head;

主要是定义指针的位置的差别,一个是在循环中定义,一个是在循环前定义,代码一在循环中反复定义next指针其实就是代码二中nextnext指针的作用,显然代码一中的next将代码二中的next和nextnext指针的作用和在一起了,更加简洁。

代码二中的指针定分工明确,思路容易想到,但是代码一在循环中定义,巧妙解决了重复元素链表删除的过程中找不到下一个节点位置的问题,显然为了解决这个问题,代码二多定义了一个指针来记录节点。

全部评论

相关推荐

评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务