链表逆序
程序员文章站
2022-03-11 21:45:39
...
链表逆序,即将原先的链表 a->b->c->d, 变为 d->c->b->a。需要使用三个指针来进行操作。
public int* reverse(int* head) {
int* front = head;
int* back = null;
int* temp;
while (front != null) {
temp = font - > next;
font -> next = back;
back = font;
font = temp;
}
return back;
}
如果要求链表两两逆序,例如 1->2->3->4 变成 2->1->4->3。该怎么呢?需要分情况处理链表长度为单数和偶数的情况。
public ListNode reverse(ListNode head) {
if (head == null)
return null;
if (head.next == null)
return head;
ListNode back = head;
ListNode front = head.next;
ListNode temp;
head = front;
while (true) {
temp = front.next;
front.next = back;
back.next = temp;
if (temp == null || (temp != null && temp.next == null))
break;
else {
front = temp.next;
back.next = front;
back = temp;
}
}
return head;
}
上一篇: 单链表的基本操作
下一篇: Window Sum