提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
为什么把这两个放在一起,因为这两个思路具有相似性
都可以通过重新排列原链表的结构实现
链接 : 203 移除链表元素



/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* removeElements(struct ListNode* head, int val){
//一些常见链表参数定义
struct ListNode* pcur = head;
struct ListNode* prev = head;
if(pcur == NULL)
{
return NULL;
}
struct ListNode* newhead = NULL;
struct ListNode* newtail = NULL;
//
while(pcur)
{
//拷贝不同的元素
if(pcur->val != val)
{
if(newhead == NULL)
{
newhead = newtail = pcur;
}
else
{
newtail->next = pcur;
newtail = newtail->next;
}
pcur = pcur->next;
}
//释放相同的元素
else
{
prev = pcur;
pcur = pcur->next;
free(prev);
}
}
//判断新的链表是否为空
if(newtail != NULL)
newtail->next = NULL;
return newhead;
}

步骤分析
为什么会想到这个方法
因为比较自然想到头插链表,头插的一个特性是 输入的数组在链表的顺序是相反的
比如: 按顺序输入 1 2 3 4 ,链表上的顺序 是 4 3 2 1

对照上方的步骤看
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* pcur = head;
if(pcur == NULL)
{
return NULL;
}
struct ListNode* plast = pcur;
struct ListNode* rehead = NULL;
while(pcur)
{
plast = pcur;
pcur = pcur->next;
//第一个元素处理
if(rehead == NULL)
{
rehead = plast;
rehead->next = NULL;
}
//其他元素处理
else
{
plast->next = rehead;
rehead = plast;
}
}
return rehead;
}
思路可以借鉴一下 空间换时间的思路,但是实际上链表空间本身是开辟的 空间复杂度是 O(1),对于数组来说也是个很好的思路