当前位置: 代码迷 >> 综合 >> 数据结构--链表基本操作
  详细解决方案

数据结构--链表基本操作

热度:98   发布时间:2024-02-08 13:40:42.0

1.链表删除其中一个元素

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode* deleteNode(ListNode* head, int val) {if(head->val==val){return head->next;}ListNode* pre=head;ListNode* cur=NULL;while(pre!=NULL){if(pre->val==val){cur->next=pre->next;cur=pre->next;if(pre->next==NULL){return head;}pre=pre->next->next;continue;}cur=pre;pre=pre->next;}return head;}
};

2.链表翻转

/*** Definition for singly-linked list.* struct ListNode {*     int val;*     ListNode *next;*     ListNode(int x) : val(x), next(NULL) {}* };*/
class Solution {
public:ListNode* reverseList(ListNode* head) {ListNode* pre=head;ListNode* cur=NULL;while(pre!=NULL){ListNode * t=pre->next;pre->next=cur;cur=pre;pre=t;}return cur;}
};