{ "type": "code_options", "author": "https://github.com/begeekmyfriend/leetcode", "source": "solution.md", "exercise_id": "04e3a587f60c4cc5aeb21d77711430f7", "keywords": "链表", "title": "反转链表 II", "desc": [ { "content": "\n给你单链表的头指针 head 和两个整数 leftright ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表

 

示例 1:

\"\"
输入:head = [1,2,3,4,5], left = 2, right = 4
输出:
[1,4,3,2,5]

示例 2:

输入:head = [5], left = 1, right = 1
输出:
[5]

 

提示:

 

进阶: 你可以使用一趟扫描完成反转吗?

", "language": "markdown" } ], "answer": [ { "content": "", "language": "cpp" } ], "prepared": [ [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ], [ { "content": "", "language": "cpp" } ] ], "template": { "content": "#include \n#include \nstruct ListNode\n{\n\tint val;\n\tstruct ListNode *next;\n};\nstatic struct ListNode *reverseBetween(struct ListNode *head, int m, int n)\n{\n\tint i;\n\tstruct ListNode dummy;\n\tstruct ListNode *prev = &dummy;\n\tprev->next = head;\n\tfor (i = 1; i < m; i++)\n\t{\n\t\tprev = prev->next;\n\t}\n\tstruct ListNode *p = prev->next;\n\tfor (i = m; i < n; i++)\n\t{\n\t\tstruct ListNode *q = p->next;\n\t\tp->next = q->next;\n\t\tq->next = prev->next;\n\t\tprev->next = q;\n\t}\n\treturn dummy.next;\n}\nint main(int argc, char **argv)\n{\n\tif (argc < 3)\n\t{\n\t\tfprintf(stderr, \"Usage: ./test m n 1 2 3...\\n\");\n\t\texit(-1);\n\t}\n\tint i, count = argc - 3;\n\tstruct ListNode dummy;\n\tstruct ListNode *prev = &dummy;\n\tstruct ListNode *p;\n\tfor (i = 0; i < count; i++)\n\t{\n\t\tp = malloc(sizeof(*p));\n\t\tp->val = atoi(argv[i + 3]);\n\t\tp->next = NULL;\n\t\tprev->next = p;\n\t\tprev = p;\n\t}\n\tint m = atoi(argv[1]);\n\tint n = atoi(argv[2]);\n\tstruct ListNode *head = reverseBetween(dummy.next, m, n);\n\tfor (p = head; p != NULL; p = p->next)\n\t{\n\t\tprintf(\"%d \", p->val);\n\t}\n\tprintf(\"\\n\");\n\treturn 0;\n}", "language": "cpp" }, "node_id": "dailycode-eef49c9c9f0943f2a27bb9f4dfb22718", "license": "csdn.net", "created_at": 1637894158, "topic_link": "https://bbs.csdn.net/topics/600469826" }