分割链表
编写程序以 x 为基准分割链表,使得所有小于 x 的节点排在大于或等于 x 的 节点之前。如果链表中包含 x,x 只需出现在小于 x 的元素之前(如下所示)。分割元素 x 只需处于“右半部分”即可,其不需要被置于左右两部分之间。
示例:
输入: head = 3->5->8->5->10->2->1, x = 5
输出: 3->1->2->10->5->5->8
链接:https://leetcode-cn.com/problems/partition-list-lcci/
//思路:双指针
//第一个指针找到第一个大于x的值
//第二个指针在第一个指针后面找到第一个小于x的值(如果没有找到则证明已经完全分割完成)
//交换两指针的值
public ListNode partition(ListNode head, int x) {
ListNode behind,front;
behind=front=head;
for (;behind!=null;behind=behind.next){
if (behind.val>=x){
for (front=behind.next;front!=null&&front.val>=x;front=front.next);
if (front==null){
break;
}
int y=front.val;
front.val=behind.val;
behind.val=y;
}
}
return head;
}
反转链表
定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
链接:https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
if (head==null){
return null;
}
if (head.next==null){
return head;
}
ListNode cur=head,prev=null;
ListNode newhead=null;
for (;cur!=null;){
ListNode after=cur.next;
if (after==null){
newhead=cur;
}
cur.next=prev;
prev=cur;
cur=after;
}
return newhead;
反转链表2.0
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii/submissions/
public ListNode reverseBetween(ListNode head, int m, int n) {
ListNode res = new ListNode(0);
res.next = head;
ListNode before = res;
for (int i = 1; i < m; i++) {
before = before.next;
}
ListNode ago = before.next;
ListNode mid = null;
ListNode after = null;
for (int i = m; i <= n; i++) {
mid = ago.next;
ago.next = after;
after = ago;
ago = mid;
}
before.next.next = mid;
before.next = after;
return res.next;
}
来源:CSDN
作者:Abraham_Tom
链接:https://blog.csdn.net/Atwood_Tom/article/details/104374016