一、单链表的存储结构
typedef struct Lnode
{
ElemType data;
struct Lnode *next;
}Lnode,*LinkList;
leetcode 203移除链表元素
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* p =new ListNode(); // 设置一个虚拟头结点
p->next = head; // 将虚拟头结点指向head,这样方面后面做删除操作
ListNode* q = p;
while(q->next!=NULL)
{
if(q->next->val==val)
{
q->next=q->next->next;
}
else
{
q=q->next;
}
}
return p->next;
}
};
leetcode 206反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
方法1:双指针法:
定义两个指针: pre 和 cur ;pre 在前 cur在后。
每次让 pre 的 next指向 cur ,实现一次局部反转
局部反转完成之后,pre 和 cur 同时往前移动一个位置
循环上述过程,直至 pre 到达链表尾部
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=head;
ListNode* cur=NULL;
while(pre!=NULL)
{
ListNode* k=pre->next;
pre->next=cur;
cur=pre;
pre=k;
}
return cur;
}
};
递归写法(有点不太理解)
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==NULL||head->next==NULL)
return head;
ListNode* k=reverseList(head->next);
head->next->next=head;
head->next=NULL;
return k;
}
};
用前插法创建一个新链表,得到的新链表为旧链表的反链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* h=new ListNode();//虚拟头结点
ListNode* p=head;
while(p!=NULL)
{
ListNode* q=p->next;//记录p->next
p->next=h->next;
h->next=p;
p=q;
}
return h->next;//由于h为虚拟头结点,真正的头结点为h->next
}
};