206&92 反转链表
206.反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
代码:
/** * 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 *p = head;//p = 1 ListNode *after; ListNode *temp; if (p == NULL) return p; after = p->next;//after = 2 p->next = NULL;//1->NULL while(after!=NULL) { temp = after->next;//temp = 3 after->next = p;//2->1 3->2 p = after;//p = 2 p = 3 after = temp;//after = 3 after = NULL } return p; } };
92 反转链表2
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
输出: 1->4->3->2->5->NULL
代码:
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { ListNode *p, *after, *temp, *end, *before; p = head; before = head; if(p == NULL) return p; int i; for(i = 1; i <= m-1; i++) { before = p; p = p->next; } end = p;//p = a[m] after = p->next;//after = a[m+1] for(i = m+1; i <= n; i++) { temp = after->next;//temp = a[m+2] temp = a[m+3] temp = NULL after->next = p;//a[m+1]->a[m] a[m+2]->a[m+1] a[m+3]->a[m+2] p = after;//p = a[m+1] p = a[m+2] p = a[m+3] after = temp; //after = a[m+2] after = a[m+3] after = NULL } end->next = after; if(m != 1) { before->next = p; return head; } else return p; } };
posted on 2020-07-24 20:21 Little-Prince 阅读(109) 评论(0) 编辑 收藏 举报