|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 糖逗 于 2020-5-8 18:02 编辑
题目描述:
- 给定单向链表的头指针和一个要删除的节点的值,定义一个函数删除该节点。
- 返回删除后的链表的头节点。
- 注意:此题对比原题有改动
- 示例 1:
- 输入: head = [4,5,1,9], val = 5
- 输出: [4,1,9]
- 解释: 给定你链表中值为 5 的第二个节点,那么在调用了你的函数之后,该链表应变为 4 -> 1 -> 9.
- 示例 2:
- 输入: head = [4,5,1,9], val = 1
- 输出: [4,5,9]
- 解释: 给定你链表中值为 1 的第三个节点,那么在调用了你的函数之后,该链表应变为 4 -> 5 -> 9.
-  
- 说明:
- 题目保证链表中节点的值互不相同
- 若使用 C 或 C++ 语言,你不需要 free 或 delete 被删除的节点
- 来源:力扣(LeetCode)
- 链接:https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof
- 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
复制代码
- #include <iostream>
- using namespace std;
- struct ListNode{
- int value;
- ListNode* next;
- ListNode(int x): value(x), next(NULL){
- }
-
- };
- void printList(ListNode* head){
- ListNode* temp = head;
- while(temp -> next != NULL){
- temp = temp -> next;
- cout << temp -> value << " ";
- }
- cout << endl;
- cout << "---------" << endl;
-
- }
- ListNode* deleteNode(ListNode* head, int val){
- ListNode* temp = head;
- ListNode* temp1 = head;
- while(temp -> next != NULL){
- temp = temp -> next;
- if(temp -> value == val){
- temp1 -> next = temp -> next;
- }
- else{
- temp1 = temp;
- }
- }
- return head;
- }
- int main(void){
- ListNode* head = new ListNode(0);
- ListNode* temp = head;
- int number;
- cout << "please send numbers that you want they to be included in singleList" << endl;
- while(cin >> number){
- ListNode* node = new ListNode(number);
- temp -> next = node;
- temp = node;
- }
- cin.clear();
- printList(head);
-
- int val;
- cout << "please send a number that you want to delete:" << endl;
- cin >> val;
- ListNode* result = deleteNode(head, val);
- printList(result);
- return 0;
- }
复制代码
|
|