第一篇终结Linked List(一)终结Linked List(二)主要讲了单链表的基础知识,接下来的第二篇主要讲一些比较经典的问题。

一、Count()

给一个单链表和一个整数,返回这个整数在链表中出现了多少次。

/*
Given a list and an int, return the number of times
that int ocucurs in the list.
*/
int Count(struct node* head,int searchFor)
{
int cnt = 0;
struct node* cur = head; while (cur != NULL)
{
if (cur->data == searchFor)
cnt++;
cur = cur->next;
} return cnt;
}

也可以用for循环实现。

二、GetNth()

给一个单链表和一个index,返回index位置上的数值,类似array[index]操作。

/*
Given a list and an index, return the data in the nth
node of the list. The nodes are numbered from 0.
Assert fails if the index is invalid (outside 0..length - 1).
*/
int GetNth(struct node* head,int index)
{
int len = 0;
struct node* cur = head; while (cur)
{
if (len == index)
{
return cur->data;
}
cur = cur->next;
len++;
} assert(0); //如果走到这一行,表达式的值为假,断言失败
}

三、DeleteList()

给一个单链表,删除所有节点,使headNULL

删除链表{1,2,3}的示意图:

void DeleteList(struct node** headRef)
{
struct node* cur = *headRef; //deref headRef to get the real head while (*headRef)
{
cur = *headRef;
*headRef = cur->next;
free(cur);
}
}

四、Pop()

给一个链表,删掉头节点,返回头节点的数据。

内存示意图:

/*
The opposite of Push().Takes a non-empty list and
remove the front node, and returns the data which was in that node.
*/
int pop(struct node** headRef)
{
assert(*headRef != NULL);
int ans = (*headRef)->data; //pull out the data before the node is deleted struct node* cur = *headRef;
*headRef = (*headRef)->next; //unlink the head node for the caller
free(cur); //free the head node return ans;
}

五、InsertNth()

可以在[0,length]的任意位置插入指定元素。

/*
A more general version of Push().
Given a list, an index 'n' in the range 0..length,
and a data element, add a new node to the list so that
it has the given index.
*/
void InsertNth(struct node** headRef,int index,int data)
{
//position 0 is a special case
if (index == 0)
{
Push(headRef, data);
}
else
{
int cnt = 0;
struct node* cur = *headRef; while (cnt < index - 1)
{
assert(cur != NULL); //if this fails, the index was too big
cur = cur->next;
cnt++;
} assert(cur != NULL); //tricky:you have to check one last time Push(&(cur->next), data);
}
}

这段代码坑有点多,可以通过画图或者单步跟踪的方法调试。

InsertNthTest()可以用来测试:

void InsertNthTest()
{
struct node* head = NULL; //start with the empty list InsertNth(&head, 0, 13); //{13}
InsertNth(&head, 1, 42); //{13,42}
InsertNth(&head, 1, 5); //{13,5,42}
}

六、SortedInsert()

给定一个有序链表和一个节点,将该节点插入到合适的位置。

共有三种方法:

1、Uses special case code for the head end

void SortedInsert(struct node** headRef,struct node* newNode)
{
//Special case for the head end
if (newNode->data <= (*headRef)->data || *headRef == NULL)
{
newNode->next = *headRef;
*headRef = newNode;
}
else
{
//Locate the node before the point of insertion
struct node* cur = *headRef;
while (cur->next && cur->next->data < newNode->data)
{
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode;
}
}

2、Dummy node strategy for the head end

dummy node这种方法一般不需要处理特殊情况。

void SortedInsert2(struct node** headRef,struct node* newNode)
{
struct node dummy;
struct node* cur = &dummy;
dummy.next = *headRef; while (cur->next && newNode->data >= cur->next->data)
{
cur = cur->next;
}
newNode->next = cur->next;
cur->next = newNode; *headRef = dummy.next; //头指针永远指向dummy.next
}

3、Local references strategy for the head end

void SortedInsert3(struct node** headRef,struct node* newNode)
{
struct node** curRef = headRef; while (*curRef && (*curRef)->data <= newNode->data)
{
curRef = &((*curRef)->next);
} newNode->next = *curRef; //Bug:(*curRef)->next is incorrect *curRef = newNode;
}

Linked List-3的更多相关文章

  1. [LeetCode] Linked List Random Node 链表随机节点

    Given a singly linked list, return a random node's value from the linked list. Each node must have t ...

  2. [LeetCode] Plus One Linked List 链表加一运算

    Given a non-negative number represented as a singly linked list of digits, plus one to the number. T ...

  3. [LeetCode] Odd Even Linked List 奇偶链表

    Given a singly linked list, group all odd nodes together followed by the even nodes. Please note her ...

  4. [LeetCode] Delete Node in a Linked List 删除链表的节点

    Write a function to delete a node (except the tail) in a singly linked list, given only access to th ...

  5. [LeetCode] Palindrome Linked List 回文链表

    Given a singly linked list, determine if it is a palindrome. Follow up: Could you do it in O(n) time ...

  6. [LeetCode] Reverse Linked List 倒置链表

    Reverse a singly linked list. click to show more hints. Hint: A linked list can be reversed either i ...

  7. [LeetCode] Remove Linked List Elements 移除链表元素

    Remove all elements from a linked list of integers that have value val. Example Given: 1 --> 2 -- ...

  8. [LeetCode] Intersection of Two Linked Lists 求两个链表的交点

    Write a program to find the node at which the intersection of two singly linked lists begins. For ex ...

  9. [LeetCode] Linked List Cycle II 单链表中的环之二

    Given a linked list, return the node where the cycle begins. If there is no cycle, return null. Foll ...

  10. [LeetCode] Linked List Cycle 单链表中的环

    Given a linked list, determine if it has a cycle in it. Follow up: Can you solve it without using ex ...

随机推荐

  1. Pyspider的基本使用

    Pyspider的基本使用 pyspider的任务流程: 每个pyspider的项目对应一个Python的脚本,该脚本中定义了一个Handler类,它有一个on_start方法.爬取首先调用on_st ...

  2. C++值多态:传统多态与类型擦除之间

    引言 我有一个显示屏模块: 模块上有一个128*64的单色显示屏,一个单片机(B)控制它显示的内容.单片机的I²C总线通过四边上的排针排母连接到其他单片机(A)上,A给B发送指令,B绘图. B可以向屏 ...

  3. Array(数组)对象-->unshift() 方法

    1.定义和用法 unshift() 方法可向数组的开头添加一个或更多元素,并返回新的长度. 语法: array.unshift(item1,item2, ..., itemX) 参数:item1,it ...

  4. 使用 RestTemplate 进行第三方Rest服务调用

    1. 前言 RestTemplate 是 Spring 提供的一个调用 Restful 服务的抽象层,它简化的同 Restful 服务的通信方式,隐藏了不必要的一些细节,让我们更加优雅地在应用中调用 ...

  5. 字典树&&AC自动机---看完大概应该懂了吧。。。。

    目录 字典树 AC自动机 字典树 又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种.典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计 ...

  6. tf.nn.sigmoid_cross_entropy_with_logits 分类

    tf.nn.sigmoid_cross_entropy_with_logits(_sentinel=None,,labels=None,logits=None,name=None) logits和la ...

  7. Volatile不保证原子性(二)

    Volatile不保证原子性 前言 通过前面对JMM的介绍,我们知道,各个线程对主内存中共享变量的操作都是各个线程各自拷贝到自己的工作内存进行操作后在写回到主内存中的. 这就可能存在一个线程AAA修改 ...

  8. animation-play-state 在 ios 中不生效的解决办法(JS篇)

    我们要实现动画的播放和暂停,animation-play-state 在安卓端可以使用,但是在 ios 中不起作用,这时可以使用 js 来实现相同效果. 原理 通过 js 获取当前元素的 transf ...

  9. 用Python介绍了企业资产情况的数据爬取、分析与展示。

    前言 文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者:张耀杰 PS:如有需要Python学习资料的小伙伴可以加点击下方链接自 ...

  10. 详解 迭代器 —— Iterator接口、 ListIterator接口 与 并发修改异常

    (请关注 本人"Collection集合"博文--<详解 Collection集合>) Iterator接口(迭代器): 概述: 对 collection 进行迭代的迭 ...